gpt4 book ai didi

python - 将正则表达式传递给 'BeautifulSoup.find_all' 不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 17:33:26 25 4
gpt4 key购买 nike

我将多个类值传递给 BeautifulSoup.find_all()。该值类似于 l4 center OR l5 center。 (即,“l4 中心”|“l5 中心”)。

soup.find_all("ul", {"class" :  value)

我使用以下两个解决方案失败(不输出任何内容):

soup.find_all("ul", {"class" :  re.compile("l[4-5]\scenter")})

#OR

soup.find_all("ul", {"class" : ["l4 center", "l5 center"]})
<小时/>

源码如下:

#!/usr/bin/env python3

from bs4 import BeautifulSoup
import bs4
import requests
import requests.exceptions
import re

### function, , .... ###
def crawler_chinese_idiom():
url = 'http://chengyu.911cha.com/zishu_8.html'
response = requests.get(url)
soup = BeautifulSoup(response.text)

#for result_set in soup.find_all("ul", class=re.compile("l[45] +center")): #l4 center or l5 center
for result_set in soup.find_all("ul", {"class", re.compile(r"l[45]\s+center")}): #nothing output
#for result_set in soup.find_all("ul", {"class" : "l4 center"}): #normal one
print(result_set)


crawler_chinese_idiom()
#[] output nothing

最佳答案

更新:已解决 https://bugs.launchpad.net/bugs/1476868

<小时/>

起初我认为问题是 HTML 中的 class='l4 center' 实际上是两个类 - 认为 soup 不匹配,因为它正在寻找包含空格的单个类(不可能)。

尝试过:

from bs4 import BeautifulSoup
import re
soup = BeautifulSoup("<html><div class='l5 center'>l5test</div><div class='l4 center'>l4test</div><div class='l6 center'>l6test</div>")

results1 = soup.findAll('div', re.compile(r'l4 center'));
print results1
results2 = soup.findAll('div', 'l4 center');
print results2

输出:

[]
[<div class="l4 center">l4test</div>]

但是等等?非正则表达式选项工作得很好 - 它找到了两个类。

在这一点上,它在我看来就像一个 BeautifulSoup bug。

要解决这个问题,您可以这样做:

soup.findAll('div', ['l4 center', 'l5 center']);
# update: ^ that doesn't work either.
# or
soup.findAll('div', ['l4', 'l5', 'center']);

我建议使用第二个,以防万一您想要匹配 l4 otherclass center,但您可能需要迭代结果以确保其中没有任何不需要的捕获。像这样的东西:

for result in soup.findAll(...):
if (result.find({'class': 'l4'}) and result.find({'class': 'center'}):
# yay!

我提交了一个错误 here供调查。

关于python - 将正则表达式传递给 'BeautifulSoup.find_all' 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31550907/

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