gpt4 book ai didi

python - BeautifulSoup .select() 方法是否支持使用正则表达式?

转载 作者:太空宇宙 更新时间:2023-11-04 08:59:20 40 4
gpt4 key购买 nike

假设我想使用 BeautifulSoup 解析 html 并且我想使用 css 选择器来查找特定标签。我会通过这样做来“简化”它

from bs4 import BeautifulSoup
soup = BeautifulSoup(html)

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

soup.select('#abc')

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

soup.select('#abc a')

但是现在,假设我想找到所有“href”属性的值以“xyz”结尾的“a”标签,我想为此使用正则表达式,我希望按照

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

我似乎找不到任何说明 BeautifulSoup 的 .select() 方法将支持正则表达式的内容。

最佳答案

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

可以使用这样的语法将结束的属性与文本匹配:

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

参见 CSS attribute selectors documentation在 MSDN 上。

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

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

请注意,作为 element.select() 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.

强调我的

关于python - BeautifulSoup .select() 方法是否支持使用正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27070690/

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