通过 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("") #问题应该出现在这个正则
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
正则有一个分组功能。。。。。。。
关键是用()进行分组提取,使用.*不一定匹配上。因为.*代表的含义是一组任意字符,但不包括换行符。
pattern = re.compile((?<=<title>)[\w\W]*(?=</title>)) pattern.search("Apple")主要是(?<=...)和(?=...)这两个表达式
这是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 会把头尾的都干掉吧