Python正则表达式后视需要固定宽度模式

时间:2010-04-10 11:43:12

标签: python html regex

在尝试提取html页面的标题时,我总是使用以下正则表达式:

(?<=<title.*>)([\s\S]*)(?=</title>)

将提取文档中标记之间的所有内容并忽略标记本身。但是,当尝试在Python中使用此正则表达式时,会引发以下异常:

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 个答案:

答案 0 :(得分:11)

抛弃使用正则表达式解析HTML的想法,并使用实际的HTML解析库。快速搜索后,我找到this one。从HTML文件中提取信息是一种更安全的方法。

请记住,HTML不是常规语言,因此正则表达式从根本上说是从中提取信息的错误工具。

答案 1 :(得分:5)

Here's a famous answer使用正则表达式解析html,这些表达非常好,“不要使用正则表达式来解析html。”

答案 2 :(得分:3)

用于提取非嵌套HTML / XML标记内容的正则表达式实际上非常简单:

r = re.compile('<title[^>]*>(.*?)</title>')

但是,对于任何更复杂的东西,你应该使用正确的DOM解析器,如urllib或BeautifulSoup。

答案 3 :(得分:2)

如下:

 r = re.compile("(<title.*>)([\s\S]*)(</title>)")
 title = r.search(page).group(2)

答案 4 :(得分:1)

如果你只想获得标题标签,

html=urllib2.urlopen("http://somewhere").read()
for item in html.split("</title>"):
    if "<title>" in item:
        print item[ item.find("<title>")+7: ]