【发布时间】:2015-02-18 23:21:32
【问题描述】:
我在 Python 中有一点屏幕抓取代码,使用 BeautifulSoup,这让我很头疼。对 html 的一个小改动使我的代码中断,但我不明白为什么它无法工作。这基本上是一个演示 html 在解析时的外观:
soup=BeautifulSoup("""
<td>
<a href="https://alink.com">
Foo Some text Bar
</a>
</td>
""")
links = soup.find_all('a',text=re.compile('Some text'))
links[0]['href'] # => "https://alink.com"
升级后,a 标签正文现在包含一个 img 标签,这使得代码中断。
<td>
<a href="https://alink.com">
<img src="dummy.gif" >
Foo Some text Bar
</a>
</td>
'links' 现在是一个空列表,所以正则表达式没有找到任何东西。 我通过仅匹配文本来绕过它,然后找到 它的父级,但这似乎更加脆弱:
links = soup.find_all(text=re.compile('Some text'))
links[0].parent['href'] # => "https://alink.com"
在文本中添加一个 img 标签作为兄弟是什么意思 内容打破了 BeautifulSoup 所做的搜索,并且在那里 修改第一个代码的方法?
【问题讨论】:
-
为什么不
next(link["href"] for link in soup.find_all('a') if "Some text" in link.text) -
看起来不错。 next() 调用是做什么的?
-
只返回第一个匹配项,这将是您想要的链接
标签: python regex beautifulsoup