首页 > 解决方案 > 使用 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 循环中的代码?

链接:https ://idn.bizdirlib.com/node/5290

标签: pythonhtmlbeautifulsoup

解决方案


您可以选择兄弟元素到<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

推荐阅读