python - Selenium 无法使用 python 抓取 Shopee 电子商务网站

标签 python selenium xpath web-scraping request

我无法在 Shopee(电子商务网站)上提取产品价格。
我查看了@dmitrybelyakov(链接:Scraping AJAX e-commerce site using python)解决的问题。

该解决方案帮助我获得了产品的“名称”和“历史销售”,但我无法获得产品的价格。我在 Json 字符串中找不到价格值。 因此,我尝试用selenium通过xpath拉取数据,但似乎失败了。

电子商务网站的链接:https://shopee.com.my/search?keyword=h370m

我的代码:

import time

from selenium import webdriver

import pandas as pd

path = r'C:\Users\\admin\\Desktop\\chromedriver_win32\\Chromedriver'

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('headless')
chrome_options.add_argument('window-size=1200x600')

browserdriver = webdriver.Chrome(executable_path = path,options=chrome_options)
link='https://shopee.com.my/search?keyword=h370m'
browserdriver.get(link)
productprice='//*[@id="main"]/div/div[2]/div[2]/div/div/div/div[2]/div/div/div[2]/div[1]/div/a/div/div[2]/div[1]'
productprice_printout=browserdriver.find_element_by_xpath(productname).text
print(productprice_printout)

当我运行该代码时,它显示了这样的错误通知:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="main"]/div/div[2]/div[2]/div/div/div/div[2]/div/div/div[2]/div[1]/div/a/div/div[2]/div[1]"}

请帮我获取Shopee上的产品价格!

最佳答案

您可以使用网站的请求和搜索 API

import requests

headers = {
    'User-Agent': 'Mozilla/5',
    'Referer': 'https://shopee.com.my/search?keyword=h370m'
}

url = 'https://shopee.com.my/api/v2/search_items/?by=relevancy&keyword=h370m&limit=50&newest=0&order=desc&page_type=search'  
r = requests.get(url, headers = headers).json()

for item in r['items']:
    print(item['name'], ' ', item['price'])

如果你想要大致相同的比例:

for item in r['items']:
    print(item['name'], ' ', 'RM' + str(item['price']/100000))

关于python - Selenium 无法使用 python 抓取 Shopee 电子商务网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55783931/

相关文章:

html - 什么 xpath 1 表达式可以对多行​​文本进行不区分大小写的匹配?

python - 从 str(datetime) 的结果获取日期时间对象

python - 当 Selenium WebDriver 作为后台进程运行时如何更改屏幕分辨率?

java - WebElement在浏览器中使用cssSelector、xpath可定位,虽然不为null,但为NotPresent、NotClickable、NotEnabled

forms - xpath - 如何选择这个提交按钮?

xml - 使用 XPath 从孙子那里获取文本并包含函数

python - 在 Python PIL 中合并图像以生成动画 gif

Python:获取转义的 SQL 字符串

python - 如何在 Keras/Tensorflow 中编写自定义损失函数,该函数使用带有引用 numpy 代码的循环/迭代

selenium - 如何处理 Selenium 中的 salesforce 悬停