BeautifulSoup.select()方法是否支持使用regex?

2024-03-29 12:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我想使用BeautifulSoup解析一个html,并且我想使用css选择器来查找特定的标记。我会把它“灵魂化”

from bs4 import BeautifulSoup
soup = BeautifulSoup(html)

如果我想找到一个“id”属性值为“abc”的标记,我可以

soup.select('#abc')

如果我想找到当前标签下的所有“a”子标签,我们可以

soup.select('#abc a')

但是现在,假设我想找到所有的“a”标记,它们的“ref”属性的值以“xyz”结尾,我想用regex来实现,我希望

soup.select('#abc a[href] = re.compile(r"xyz$")')

我似乎找不到任何关于BeautifulSoup.select()方法将支持regex的内容。


Tags: from标记属性html选择器标签selectcss
1条回答
网友
1楼 · 发布于 2024-03-29 12:22:25

soup.select()函数只支持CSS语法;正则表达式不属于该语法的一部分。

您可以使用这样的语法将结束于文本的属性匹配起来:

soup.select('#abc a[href$="xyz"]')

请参阅MSDN上的CSS attribute selectors documentation

您始终可以使用CSS选择器的结果继续搜索:

for element in soup.select('#abc'):
    child_elements = element.find_all(href=re.compile('^http://example.com/\d+.html'))

注意,作为^{} documentation states

This is a convenience for users who know the CSS selector syntax. You can do all this stuff with the Beautiful Soup API. And if CSS selectors are all you need, you might as well use lxml directly: it’s a lot faster, and it supports more CSS selectors. But this lets you combine simple CSS selectors with the Beautiful Soup API.

强调我的。

相关问题 更多 >