在python中使用正则表达式的问题

2 html python regex

好吧,所以我正在使用正则表达式来搜索站点中的所有标题信息.

我编译了正则表达式:

regex = re.compile(r'''
    <h[0-9]>\s?
    (<a[ ]href="[A-Za-z0-9.]*">)?\s?
    [A-Za-z0-9.,:'"=/?;\s]*\s?
    [A-Za-z0-9.,:'"=/?;\s]?
''',  re.X)
Run Code Online (Sandbox Code Playgroud)

当我在python reg ex中运行它时.测试员,它非常好用.

样本数据:

<body>
    <h1>Dog </h1>
    <h2>Cat </h2>
    <h3>Fancy </h3>
    <h1>Tall cup of lemons</h1>
    <h1><a href="dog.com">Dog thing</a></h1>
</body>
Run Code Online (Sandbox Code Playgroud)

现在,在REDemo中,它运行得非常好.

但是,当我把它放在我的python代码中时,它只会打印出来 <a href="dog.com">

这是我的python代码,我不确定我是做错了什么还是翻译时丢失了什么.我感谢您的帮助.

stories=[]
response = urllib2.urlopen('http://apricotclub.org/duh.html')
html = response.read().lower()
p = re.compile('<h[0-9]>\\s?(<a href=\"[A-Za-z0-9.]*\">)?\\s?[A-Za-z0-9.,:\'\"=/?;\\s]*\\s?[A-Za-z0-9.,:\'\"=/?;\\s]?')
stories=re.findall(p, html)
for i in stories:
    if len(i) >= 5:
        print i 
Run Code Online (Sandbox Code Playgroud)

我还应该注意,当我(<a href=\"[A-Za-z0-9.]*\">)?从正则表达式中取出它时,它适用于非链接<hN>行.

Jer*_*rub 23

在过去的几天里,这个问题已经以多种形式提出,所以我将非常清楚地说出这个问题.

问:如何使用正则表达式解析HTML?

A:请不要.

使用BeautifulSoup,html5liblxml.html.请.