使用Web Scratching获取商品价格



我想制作一个Python脚本,但不幸的是,当我想检查价格时,我得到的是NONE,而不是价格本身(如果我更改代码,则为00.00美元(。我发现了很多例子,其中HTMLid一起使用,但我不知道如何使用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)

BeautifulSoup在网站使用Javascript并动态更改时对web抓取的使用非常少。现在大多数网站都使用Javascript,很难抓取数据。另一种选择是使用Selenium

如果您已经使用了Selenium,那么直接跳到下面的代码块。如果没有,请按照以下说明进行操作。

  1. 在选项菜单(浏览器右上角(下检查您在About Chrome中使用的Chrome版本
  2. 转到此网站并下载相同版本的驱动程序
  3. 创建一个文件夹C:webdrivers,并将下载的驱动程序复制到此文件夹中
  4. 复制文件路径C:webdriverschromedriver.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:webdriverschromedriver.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的更多详细信息,请参阅文档,这是一个令人印象深刻的模块!

最新更新