我注意到findAll
方法的一些奇怪行为:
>>> htmls="<html><body><p class=\"pagination-container\">slytherin</p><p class=\"pagination-container and something\">gryffindor</p></body></html>"
>>> soup=BeautifulSoup(htmls, "html.parser")
>>> for i in soup.findAll("p",{"class":"pagination-container"}):
print(i.text)
slytherin
gryffindor
>>> for i in soup.findAll("p", {"class":"pag"}):
print(i.text)
>>> for i in soup.findAll("p",{"class":"pagination-container"}):
print(i.text)
slytherin
gryffindor
>>> for i in soup.findAll("p",{"class":"pagination"}):
print(i.text)
>>> len(soup.findAll("p",{"class":"pagination-container"}))
2
>>> len(soup.findAll("p",{"class":"pagination-containe"}))
0
>>> len(soup.findAll("p",{"class":"pagination-contai"}))
0
>>> len(soup.findAll("p",{"class":"pagination-container and something"}))
1
>>> len(soup.findAll("p",{"class":"pagination-conta"}))
0
因此,当我们搜索pagination-container
时,它同时返回第一个和第二个p
标记。它让我认为它寻找的是部分相等:类似于if passed_string in class_attribute_value:
。所以我缩短了findAll
方法中的字符串,它从来没有找到任何东西!在
怎么可能?在
首先,^{} 是一个特殊的multi-valued space-delimited attribute,并且具有特殊的处理方式。在
当您编写
soup.findAll("p", {"class":"pag"})
时,BeautifulSoup
将搜索具有pag
类的元素。它将按空格分隔元素类值,并检查拆分的项中是否有pag
。如果有一个带有class="test pag"
或class="pag"
的元素,那么它将是匹配的。在注意,在
soup.findAll("p", {"class": "pagination-container and something"})
的情况下,BeautifulSoup
将匹配具有确切的class
属性值的元素。在这个例子中没有涉及到拆分——它只看到一个元素,其中完整的class
值等于所需的字符串。在要使某个类的部分匹配,可以提供一个regular expression或a function作为类筛选器值:
还有很多要说的,但是您还应该知道
^{pr2}$BeautifulSoup
支持CSS selector(这是一个有限的支持,但涵盖了大多数常见的用例)。你可以这样写:处理
BeautifulSoup
中的class
属性值是常见的混淆和问题,请参阅以下相关主题以获得更多理解:相关问题 更多 >
编程相关推荐