Python正则表达式反向查找需要固定宽度模式
在提取网页标题的时候,我一直使用以下的正则表达式:
(?<=<title.*>)([\s\S]*)(?=</title>)
这个表达式可以提取文档中
Traceback (most recent call last):
File "test.py", line 21, in <module>
pattern = re.compile('(?<=<title.*>)([\s\S]*)(?=</title>)')
File "C:\Python31\lib\re.py", line 205, in compile
return _compile(pattern, flags)
File "C:\Python31\lib\re.py", line 273, in _compile
p = sre_compile.compile(pattern, flags) File
"C:\Python31\lib\sre_compile.py", line 495, in compile
code = _code(p, flags) File "C:\Python31\lib\sre_compile.py", line 480, in _code
_compile(code, p.data, flags) File "C:\Python31\lib\sre_compile.py", line 115, in _compile
raise error("look-behind requires fixed-width pattern")
sre_constants.error: look-behind requires fixed-width pattern
我使用的代码是:
pattern = re.compile('(?<=<title.*>)([\s\S]*)(?=</title>)')
m = pattern.search(f)
如果我稍微调整一下,它就能正常工作:
pattern = re.compile('(?<=<title>)([\s\S]*)(?=</title>)')
m = pattern.search(f)
不过,这样做并没有考虑到可能存在的带有属性的html标题,或者其他类似的情况。
有没有人知道解决这个问题的好办法?任何建议都很欢迎。
5 个回答
6
这里有一个著名的回答,讲的是用正则表达式解析HTML的事情,它很好地说明了“不要用正则表达式来解析HTML”。
13
别想着用正则表达式来解析HTML,还是用真正的HTML解析库吧。经过简单搜索,我找到了这个。这样提取HTML文件中的信息要安全得多。
记住,HTML不是一种普通的语言,所以用正则表达式来提取信息根本就不合适。
2
如果你只是想获取标题标签,
html=urllib2.urlopen("http://somewhere").read()
for item in html.split("</title>"):
if "<title>" in item:
print item[ item.find("<title>")+7: ]