【问题标题】:Why does my python regex code not work properly? [duplicate]为什么我的 python 正则表达式代码不能正常工作? [复制]
【发布时间】:2014-06-26 09:57:40
【问题描述】:

晚上好。 我得到以下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'

【问题讨论】:

    标签: python html regex html-parsing


    【解决方案1】:

    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'
    

    【讨论】:

    • 哦,太棒了,我没想到。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 2019-01-22
    相关资源
    最近更新 更多