【问题标题】:Getting item price with Web Scraping使用 Web Scraping 获取商品价格
【发布时间】:2021-01-02 19:06:19
【问题描述】:

我想制作一个 Python 脚本,但不幸的是,当我想查看价格时,我得到的是NONE 而不是价格本身(如果我更改代码,则为 00.00 美元) . 我找到了很多例子,其中 HTML 与id 一起使用,但我不知道应该如何使用class。

到目前为止我所拥有的:

import requests
from bs4 import BeautifulSoup


URL = 'https://www.banggood.com/BlitzWolf-BW-LT32-2M-USB-RGB-TV-Strip-Light-Kit-Sync-with-TV-Screen-Color-3-Sides-Cover-for-TV-Vivid-RGB-Color-Lighting-Effect-and-Dual-Simple-Control-p-1785284.html?akmClientCountry=HU&channel=facebookads&utm_source=facebookads&utm_medium=cpc&utm_campaign=app-dpa-all-ww-sm-afpur180-0407_prdshare_msg&utm_content=suki&utm_design=-&fbclid=IwAR3cAovrze4opttuwwpUxnXZ6dkRjhau3RqmDqASPW0mSEOI8sJgn9Cqss8&_branch_match_id=850392564428961100&cur_warehouse=CN&ID=45764'

headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537'}

page = requests.get(URL, headers=headers)

soup = BeautifulSoup(page.content, 'html.parser')

    title = soup.find("span",{"class":'product-title-text'}).get_text()
    price = soup.find("span",{"class":'main-price'}).get_text()


converted_price = price[0:5]

print(converted_price)
print(title)

【问题讨论】:

  • 请包含 HTML 示例并说明您要提取哪些部分。
  • 该商品现在更便宜了,我需要 26.88
    US$26.88 US$49.99 -46%
  • 感谢您的更新,但请edit您的问题。

标签: python web scrape price


【解决方案1】:

BeautifulSoup 在网站使用 Javascript 并动态更改时对网络抓取的使用非常少。如今,大多数网站都使用 Javascript,因此难以抓取数据。另一种选择是使用Selenium。

如果你已经用过Selenium那么直接跳转到下面的代码块。如果没有,请按照以下说明操作。

  1. 在选项菜单(浏览器右上角)下的About Chrome 中查看您正在使用的 Chrome 版本。
  2. 访问this网站并下载相同版本的驱动程序。
  3. 创建一个文件夹C:\webdrivers,并将下载的驱动复制到这个文件夹中。
  4. 复制文件路径C:\webdrivers\chromedriver.exe并将其添加到environment variables中的PATH中(

现在执行下面的代码:

from selenium import webdriver

opts = webdriver.ChromeOptions()
# The below line will make your browser run in background when uncommented
# opts.add_argument('--headless')
    
driver = webdriver.Chrome(options= opts, executable_path = 'C:\webdrivers\chromedriver.exe')

driver.get("https://www.banggood.in/BlitzWolf-BW-LT32-2M-USB-RGB-TV-Strip-Light-Kit-Sync-with-TV-Screen-Color-3-Sides-Cover-for-TV-Vivid-RGB-Color-Lighting-Effect-and-Dual-Simple-Control-p-1785284.html?akmClientCountry=HU&channel=facebookads&utm_source=facebookads&utm_medium=cpc&utm_campaign=app-dpa-all-ww-sm-afpur180-0407_prdshare_msg&utm_content=suki&utm_design=-&_branch_match_id=850392564428961100&cur_warehouse=CN&ID=45764")

prices = driver.find_elements_by_class_name('main-price')

for price in prices:
    print(price.text)
driver.quit()

输出:

₹1,712.63

有关Selenium的更多详细信息,请访问documentation,这是一个令人印象深刻的模块!

【讨论】:

  • 非常感谢您的快速帮助和详细解答!
猜你喜欢
相关资源
最近更新 更多
热门标签