【问题标题】:not desired output in web scraping in bs4bs4 网络抓取中不需要的输出
【发布时间】:2022-01-25 11:02:12
【问题描述】:

我正在抓取产品信息。但是我刮掉了它的价格,它没有给我适当的输出。没有错误但不是所需的输出。

而且在查找产品类别时也会产生错误。 这是我的代码。

import requests
from bs4 import BeautifulSoup as bs
import pandas

url='https://shop.eziline.com/product/uncategorized/umrah-management-system/'
r=requests.get(url)
soup=bs(r.content,'html.parser')

name=soup.find(class_='product_title entry-title').text.strip()
print(name)
price=soup.find('span',class_='woocommerce-Price-amount amount').text.strip()
print(price)
detail=soup.find(class_='woo-product-details_short-description').text.strip()
print(detail)
category=soup.find('cats-link a').text.strip()
print(category)

【问题讨论】:

  • 它给了我输出 R.s 0.00

标签: python beautifulsoup jupyter scrape


【解决方案1】:

您在find方法中使用的属性应用于多个标签,您可以使用findAll查看所有标签,如下:

for t in soup.findAll('span',class_='woocommerce-Price-amount amount'):
    print(str(t) + "\n")

这将导致以下输出

<span class="woocommerce-Price-amount amount"><bdi>0.00<span class="woocommerce-Price-currencySymbol">$</span></bdi></span>

<span class="woocommerce-Price-amount amount"><bdi>0.00<span class="woocommerce-Price-currencySymbol">$</span></bdi></span>

<span class="woocommerce-Price-amount amount">350.00<span class="woocommerce-Price-currencySymbol">$</span></span>

<span class="woocommerce-Price-amount amount"><bdi>850.00<span class="woocommerce-Price-currencySymbol">$</span></bdi></span>

在您的代码中,find 方法返回带有类woocommerce-Price-amount amountspan 的第一次出现,因此输出为0.00

只获取您可以使用的价格的最后一个标签

price = soup.findAll('span',class_='woocommerce-Price-amount amount')[-1].text.strip()

【讨论】:

    【解决方案2】:

    你是

    1. 选择第一个价格而不是目标价格。相反,您可以使用主要内容 id 作为正确部分的锚,以从

      返回价格
    2. 您试图在最后一行中使用 css 选择器语法,而没有通过适当的方法应用并添加类选择器的语法。你也可以使用category=soup.find(class_='cats-link').a.text.strip()

    改为:

    import requests
    from bs4 import BeautifulSoup as bs
    
    url='https://shop.eziline.com/product/uncategorized/umrah-management-system/'
    r=requests.get(url)
    soup=bs(r.content,'lxml')
    name=soup.find(class_='product_title entry-title').text.strip()
    print(name)
    price=soup.select_one('#main-content .woocommerce-Price-amount bdi').text.strip()
    print(price)
    detail=soup.find(class_='woo-product-details_short-description').text.strip()
    print(detail)
    category=soup.select_one('.cats-link a').text.strip()
    print(category)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 2020-09-16
      • 2020-03-21
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      相关资源
      最近更新 更多