BS4 抓取具有不寻常属性的标签的内容

BS4 grabbing the contents of a tag with an unusual attribute

我正在使用 BS4 抓取一个网站(我们有权抓取但无法控制 html)并且他们稍微更改了格式。这种变化意味着我想不出一个小段的方法。

这是html

<p class="icons"> 
<span data-caption=" Bed"> 8</span>            
<span data-caption=" Bath">4</span>            
<span data-caption=" Car">4</span>            
<span data-caption="">1090m&sup2;        
</p>        

我正在尝试使用

获取床位数量
bed = soup.find("span",{"data-caption":" Bed"})

然后使用

清理它
bed = bed.replace(" ","")

但每次床位都设置为none。关于如何抓住它的任何见解?

使用strip函数去除所有前导或尾随空格。 .text 帮助您获取特定标签的内容。

>>> s = """<p class="icons"> 
<span data-caption=" Bed"> 8</span>            
<span data-caption=" Bath">4</span>            
<span data-caption=" Car">4</span>            
<span data-caption="">1090m&sup2;        
</p> """
>>> soup = BeautifulSoup(s)
>>> soup.find("span",{"data-caption":" Bed"}).text.strip()
'8'

您正尝试在元素上使用 replace 方法 :

>>> soup.find("span",{"data-caption":" Bed"})
<span data-caption=" Bed"> 8</span>
>>> soup.find("span",{"data-caption":" Bed"}).replace(' ', '')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

BeautifulSoup 允许您仅按名称查找元素,作为属性。任何 BeautifulSoup 不理解的属性都会变成 search 以查找具有该名称的元素。

因为您在元素上使用了名称 .replace,BeautifulSoup 正在尝试查找 <replace> 元素。没有这样的元素,所以返回 None

>>> soup.find("span",{"data-caption":" Bed"}).replace is None
True

您只需使用 element.get_text() method:

>>> soup.find("span",{"data-caption":" Bed"}).get_text()
u' 8'

您可以给它一个 strip 关键字参数,将其设置为 True 以便为您去除文本元素(从开始和结束删除空格):

>>> soup.find("span",{"data-caption":" Bed"}).get_text(strip=True)
u'8'