为什么我的python正则表达式代码无法正常工作?

时间:2014-05-08 20:00:37

标签: python html regex html-parsing

晚上好。 我得到了以下HTML代码:

<tr>
   <td>value:</td>
   <td>0</td>
</tr>

此代码是完整html网页的一部分。 我想解析第二个td-tag中的值。

这是我的尝试:

pattern = re.compile('<td>value:</td>.*?<td>(.*?)</td>', re.S)
value = pattern.search(source_code).group(1)

source_code是完整的网页源代码。

当我运行此代码时,我收到以下消息: AttributeError: 'NoneType' object has no attribute 'group'

1 个答案:

答案 0 :(得分:5)

Do not parse HTML with regex

相反,使用专门的工具,html解析器,如BeautifulSoup

>>> from bs4 import BeautifulSoup
>>> data = """<tr>
...    <td>value:</td>
...    <td>0</td>
... </tr>"""
>>> soup = BeautifulSoup(data)
>>> soup.find('tr')('td')[1].text
u'0'
>>> soup.find('td', text='value:').find_next_sibling('td').text
u'0'