【问题标题】:How to extract data from HTML using beuatiful soup如何使用 Beautifulsoup 从 HTML 中提取数据
【发布时间】:2019-05-24 06:47:55
【问题描述】:

我正在尝试抓取网页并将结果存储在 csv/excel 文件中。我正在为此使用美味的汤。

我正在尝试使用 find_all 函数从汤中提取数据,但我不确定如何捕获字段名称或标题中的数据

HTML 文件具有以下格式

<h3 class="font20">
 <span itemprop="position">36.</span> 
 <a class="font20 c_name_head weight700 detail_page" 
 href="/companies/view/1033/nimblechapps-pvt-ltd" target="_blank" 
 title="Nimblechapps Pvt. Ltd."> 
     <span itemprop="name">Nimblechapps Pvt. Ltd. </span>
</a> </h3>

到目前为止,这是我的代码。不知道如何从这里开始

from bs4 import BeautifulSoup as BS
import requests 
page = 'https://www.goodfirms.co/directory/platform/app-development/iphone? 
page=2'
res = requests.get(page)
cont = BS(res.content, "html.parser")
names = cont.find_all(class_ = 'font20 c_name_head weight700 detail_page')
names = cont.find_all('a' , attrs = {'class':'font20 c_name_head weight700 
detail_page'})

我尝试过使用以下 -

Input: cont.h3.a.span
Output: <span itemprop="name">Nimblechapps Pvt. Ltd.</span>

我想提取公司名称——“Nimblechapps Pvt. Ltd.”

【问题讨论】:

  • 贴出你试过的代码,具体问题是什么。
  • @ScottHunter 完成!请检查问题的编辑版本
  • 你想要cont.h3.a.span.text
  • 获取标签属性使用tag[attr],获取标签文本使用tag.text。请注意,.find_all() 返回一个元素列表。如果您只想第一次使用.find() 或按索引选择。
  • 简单,选择每个元素的文本,例如:for tag in cont.find_all("span", itemprop="name"): print(tag.text)

标签: python html web-scraping beautifulsoup


【解决方案1】:

您可以为此使用列表推导:

from bs4 import BeautifulSoup as BS
import requests

page = 'https://www.goodfirms.co/directory/platform/app-development/iphone?page=2'
res = requests.get(page)
cont = BS(res.content, "html.parser")
names = cont.find_all('a' , attrs = {'class':'font20 c_name_head weight700 detail_page'})
print([n.text for n in names])

你会得到:

['Nimblechapps Pvt. Ltd.', (..) , 'InnoApps Technologies Pvt. Ltd', 'Umbrella IT', 'iQlance Solutions', 'getyoteam', 'JetRuby Agency LTD.', 'ONLINICO', 'Dedicated Developers', 'Appingine', 'webnexs']

【讨论】:

    【解决方案2】:

    同样的事情,但使用后代组合器 " " 将类型选择器 a 与属性 = 值选择器 [itemprop="name"] 组合起来

    names = [item.text for item in cont.select('a [itemprop="name"]')]
    

    【讨论】:

      【解决方案3】:

      尽量不要在脚本中使用复合类,因为它们容易损坏。以下脚本也应该为您获取所需的内容。

      import requests
      from bs4 import BeautifulSoup
      
      link = "https://www.goodfirms.co/directory/platform/app-development/iphone?page=2"
      
      res = requests.get(link)
      soup = BeautifulSoup(res.text, 'html.parser')
      for items in soup.find_all(class_="commoncompanydetail"):
          names = items.find(class_='detail_page').text
          print(names)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-29
        • 2013-01-29
        • 1970-01-01
        • 2021-04-24
        • 1970-01-01
        • 2015-04-13
        • 2013-11-15
        • 1970-01-01
        相关资源
        最近更新 更多