我将多个类值传递给BeautifulSoup.find_all()
。该值类似于l4 center
或l5 center
。 (即,"l4 center" | "l5 center"
)。将正则表达式传递给'BeautifulSoup.find_all'不起作用
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
尝试're.compile(r“l [45] \ s + center”)'。没有'r',你需要使用''s'',并且'[45]'已经意味着4或者5. –
你是什么意思*它不起作用*? – styvane
你的数据是什么样的? – hwnd