gpt4 book ai didi

Python - Bs4 正则表达式将结果匹配到[]

转载 作者:行者123 更新时间:2023-12-01 03:51:15 25 4
gpt4 key购买 nike

我使用 regextester101 来确认我的正则表达式没有错误,因为它确实在 HTML 页面中找到了以下 id 之一的匹配项:pj_8c1bde71686c6c05

我正在尝试抓取的页面:http://www.indeed.ca/help-desk-jobs-in-ON

我使用 html 文件作为测试的 ID:pj_8c1bde71686c6c05

bs4 = BeautifulSoup(search_result_contents, "html.parser")
result = bs4.find_all('div', re.compile('id_=p\w*_\w*'))
print(result)

打印结果:

[]
[]
[]
[]

最佳答案

如果您希望将正则表达式应用于 id 属性,则需要使用 id 参数。另外,您需要使用“原始”字符串并修复正则表达式:

bs4.find_all('div', id=re.compile(r'pj_\w+'))

此处 pj_\w+ 将匹配 pj,后跟下划线,后跟一个或多个字母数字字符。

演示:

>>> import re
>>> import requests
>>> from bs4 import BeautifulSoup
>>>
>>> url = "http://www.indeed.ca/help-desk-jobs-in-ON"
>>>
>>> response = requests.get(url)
>>>
>>> soup = BeautifulSoup(response.content, "html.parser")
>>> soup.find_all('div', id=re.compile(r'pj_\w+'))
[<div class="row result" data-jk="13fdade4fb44d84f" id="pj_13fdade4fb44d84f">\n...
>\n</div>\n<span class="sdn">Sponsored</span>\n</br></div>]
<小时/>

或者,您可以使用“开头为”CSS selector :

bs4.select("div[id^=pj_]")

关于Python - Bs4 正则表达式将结果匹配到[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38214681/

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