gpt4 book ai didi

python - 正则表达式 - 从 HTML 读取日期

转载 作者:行者123 更新时间:2023-12-01 05:36:10 25 4
gpt4 key购买 nike

如果有人能告诉我这段代码做错了什么,我会很伤心。我有一个 HTML,想要读出成立年份 - 在本例中是 1949。我该怎么办呢?请注意空格和空行。

下面是代码

<h4>  Founded in

</h4></td><td><h5> <!--10305--> 1949</h5></td></tr> <tr>

这是我正在使用的代码。并且没有打印任何内容。

myf = 'THE HTML HERE'
myf.replace("<!--10305-->", "")
year = re.findall(r"<h4> Founded in.*? (.*?)</h5></td></tr> <tr>", myf, re.DOTALL)
print year

如有任何帮助,我们将不胜感激。

最佳答案

使用lxml使用 xpath:

>>> import lxml.html
>>>
>>> root = lxml.html.fromstring('''
... <tr>
... <td>
... <h4> Founded in
...
... </h4></td><td><h5> <!--10305--> 1949</h5></td></tr>
... ''')
>>> root.xpath('//h4[contains(text(), "Founded in")]/parent::*/following-sibling::*')[0].text_content().strip()
'1949'

关于python - 正则表达式 - 从 HTML 读取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19008695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com