BeautifulSoup findall使用正则表达式来查找A类或B类

时间:2015-07-21 16:18:06

标签: regex python-3.x beautifulsoup html-parsing bs4

我试图按顺序查找class =“A”和class =“B”。换句话说,我想使用OR运算符,因此它以正确的顺序打印出结果。以下是我的尝试和结果:

#Attempt #1
print(soup.find_all("li", attrs={"class": re.compile(r"Some Text A|Some Text B" )}))

#Attempt #2
soup.findAll("li", {'class':['Some Text A', 'Some Text B']})

#Attempt #3
print(soup.find_all("li", class_= re.compile(r"Some Text A|Some Text B" )))

所有尝试都给了我一个空列表作为结果,但应该有46个结果。我可以单独完成两个课程,但我无法弄清楚如何同时完成这些课程。重要的是要注意,这两个类不是同时归属于同一个li,而是两个输出不同结果的不同类。

到目前为止,还没有堆栈溢出的答案。我正在使用python 3.4和Beautifulsoup 4

1 个答案:

答案 0 :(得分:0)

我找到了部分解决方案。出于某种原因,当字符串“A”或/和字符串“B”包含空格时,正则表达式将无法正常工作。例如:

这不起作用:

print(soup.find_all("li", attrs={"class": re.compile(r"Some Text A|Some Text B" )}))

然而这有效:

print(soup.find_all("li", attrs={"class": re.compile(r"A|B" )}))

谢天谢地,我的字符串仍然足够精确,同时排除了空格后的文字。对于涉及使用正则表达式时包含空格的字符串的搜索,我将不胜感激。