Skip to main content
 首页 » 编程设计

python之使用BeautifulSoup提取div内的页面信息

2025年05月04日25lori

我正在尝试从 div 类中提取页数(在本例中为 156)。代码如下所示。

   <div class="listing-count-label listing-count-holder listing-count-holder-header">8007 listings, showing 1 to 156</div> 

我目前有:

page = soup.find("div",{"class":"listing-count-label listing-count-holder listing-count-holder-header"}) 
for x in page: 
    print (x.text) 

产量:

[ ]

最终我想要 page = 156.

请您参考如下方法:

问题是,find() 返回一个单个元素(一个Tag 实例),它也可以是可迭代的 - 你将迭代元素的子元素。而且,由于只有一个 child - 一个文本节点,@Dekel 的答案会起作用。

但是,您实际上并不需要 for 循环,可以直接简单地获取文本:

page = soup.find("div", {"class":"listing-count-label listing-count-holder listing-count-holder-header"}) 
print(page.get_text()) 

另外,你真的不需要列出一个元素的所有类来定位它,你可以使用一个:

soup.find("div", class_="listing-count-label") 

或者,使用 CSS selector :

soup.select_one("div.listing-count-label") 

但是,既然您已经达到了页数,我们为什么不使用 regular expression 通过文本定位元素呢? - 而且,我们将使用相同的正则表达式来提取页数:

>>> import re 
>>> from bs4 import BeautifulSoup 
>>>  
>>> data = """<div class="listing-count-label listing-count-holder listing-count-holder-header">8007 listings, showing 1 to 156</div>""" 
>>>  
>>> pattern = re.compile(r"\d+ listings, showing \d+ to (\d+)") 
>>>  
>>> soup = BeautifulSoup(data, "html.parser") 
>>>  
>>> pattern.search(soup.find(text=pattern)).group(1) 
u'156' 

并且,您可以使用 int() 将其转换为整数。但是,此代码缺少错误处理 - 事情可能会出错 - 请确保正确处理错误。