python - 使用 beautifulsoup 提取网页中所有 url 中的公司名称和其他信息
问题描述
<li>
<strong>Company Name</strong>
":"
<span itemprop="name">PT ERA MURNI BUSANA</span>
</li>
在上面的 HTML 代码中,我试图提取公司名称 PT ERA MURNI BUSANA。如果我使用单个测试链接,我可以使用我编写的单行代码获取名称:
soup.find_all("span",attrs={"itemprop":"name"})[3].get_text()
但我想从单个网页中的所有此类页面中提取信息。所以我写了 for 循环,但它是获取详细信息。我正在粘贴我一直在尝试的需要修改的代码部分。代码:-
for link in supplierlinks: #links have been extracted and merged with the base url
r=requests.get(link,headers=headers)
soup=BeautifulSoup(r.content,'lxml')
companyname=soup.find_all("span",attrs={"itemprop":"name"})[2].get_text()
输出如下所示:
{'公司名称': 'AIRINDO SAKTI GARMENT PT'}
{'公司名称': '服装'}
{'公司名称': '服装'}
我需要的是公司名称,而不是输出中出现的服装。如何修改 for 循环中的代码?
解决方案
您可以选择兄弟元素到<strong>
包含文本的元素"Company Name"
(另外,不要忘记设置 User-Agent http 标头):
import requests
from bs4 import BeautifulSoup
url = 'https://idn.bizdirlib.com/node/5290'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0'}
soup = BeautifulSoup(requests.get(url, headers=headers).content, 'html.parser')
print( soup.select_one('strong:contains("Company Name") + *').text )
印刷:
PT ERA MURNI BUSANA
编辑:获取联系人:
import requests
from bs4 import BeautifulSoup
url = 'https://idn.bizdirlib.com/node/5290'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0'}
soup = BeautifulSoup(requests.get(url, headers=headers).content, 'html.parser')
print( soup.select_one('strong:contains("Company Name") + *').text )
print( soup.select_one('strong:contains("Contact") + *').text )
印刷:
PT ERA MURNI BUSANA
Mr. Yohan Kustanto
推荐阅读
- c# - 页面刷新后如何在浏览器中保存弹出对话?
- okta-signin-widget - sessionCookieRedirect 调用后获取 okta 欢迎页面
- rest - Delphi REST 和 Unicode 字符不存在映射
- python - 博客类别 Slugify 在 Django 中不起作用
- java - 在 Javafx 中更改线条的颜色
- java - 无法在 spring boot jar 中运行命令 cucumber - 未找到后端。请确保您的 CLASSPATH 上有一个后端模块
- docker - QueryTree 测试连接返回 404 not found
- python - 如何在python中将整数月转换为年
- java - Kie 服务器:如何部署具有依赖项的 kjar 容器
- electron - Electron 应用程序可以处理单独的窗口吗?