美丽汤(BeautifulSoup)获取标签中的文本

3

我想从黄页获取数据,但我只需要数字管道工。但我无法在h2 class='n'中获取文本数字。我可以获取class="business-name"的文本,但我只需要数字管道工而不包括广告。我错在哪里?非常感谢。

这是html代码:

<div class="info">
   <h2 class="n">1.&nbsp;<a class="business-name" href="/austin-tx/mip/johnny-rooter-11404675?lid=171372530" rel="" data-impressed="1"><span>Johnny Rooter</span></a></h2>
</div>

这是我的Python代码:

import requests
from bs4 import BeautifulSoup as bs

url = "https://www.yellowpages.com/austin-tx/plumbers"
req = requests.get(url)
data = req.content
soup = bs(data, "lxml")
links = soup.findAll("div", {"class": "info"})

for link in links:
        for content in link.contents:
            try:
                print(content.find("h2", {"class": "n"}).text)
            except:
                pass
1个回答

0

您需要一个不同的类选择器来限制到该部分

import requests
from bs4 import BeautifulSoup as bs

url = "https://www.yellowpages.com/austin-tx/plumbers"
req = requests.get(url)
data = req.content
soup = bs(data, "lxml")
links = [item.text.replace('\xa0','') for item in soup.select('.organic h2')]
print(links)

.organic 是一个单类选择器,用于表示一个父元素中的复合类,并且仅限于所有编号的水管工。请注意,在广告后面开始突出显示的方式:

enter image description here


输出:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接