我将多个类值传递给BeautifulSoup.find_all()。这个值类似于l4 center 或 l5 center。(即"l4 center" | "l5 center")。
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发布于 2015-07-21 23:34:09
更新:已解决的https://bugs.launchpad.net/bugs/1476868
起初,我认为问题在于,class='l4 center'中的HTML实际上是两个类--认为“汤”是不匹配的,因为它在寻找一个包含空格的类(不可能)。
试过:
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!我已经提交了一个bug 这里供调查。
https://stackoverflow.com/questions/31550907
复制相似问题