python如何正确抓取网页标题
巴扎黑
巴扎黑 2017-04-17 11:01:55
[Python讨论组]

通过 urllib 将网页内容抓取下来,然后用正则表达式 re 模块将标题匹配出来,但是发现部分标题会出现问题,比如下面抓 Apple 的代码运行结果是 App,测试发现匹配结果 m 是没有问题的,问题出现在了 strip() 这里。

# -*- coding: utf-8 -*-
import urllib
import re

url='http://apple.com'
html = urllib.urlopen(url).read()
#print html
m = re.search(".*", html)
print m.group() # 这里输出结果 Apple
print m.group().strip("") #问题应该出现在这个正则
巴扎黑
巴扎黑

全部回复(5)
怪我咯
re.findall(r"<title>(.*)</title>","<title>Apple</title>")

正则有一个分组功能。。。。。。。

PHPz

关键是用()进行分组提取,使用.*不一定匹配上。因为.*代表的含义是一组任意字符,但不包括换行符。

黄舟
pattern = re.compile((?<=<title>)[\w\W]*(?=</title>))
pattern.search("Apple")

主要是(?<=...)和(?=...)这两个表达式

ringa_lee

这是strip的help

`Help on method_descriptor:

strip(...)
S.strip([chars]) -> string or unicode

Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping`

title中包涵le, 所以apple里的le被strip掉了

阿神

strip 会把头尾的都干掉吧

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号