【发布时间】:2021-07-31 23:11:09
【问题描述】:
但是它总是返回 null:
我的代码:
'price' :response.xpath('//*[contains(@class, "current-price")]').get()
有人可以帮忙吗?
谢谢!
如何检索价格?
【问题讨论】:
标签: python selenium web-scraping xpath scrapy
但是它总是返回 null:
我的代码:
'price' :response.xpath('//*[contains(@class, "current-price")]').get()
有人可以帮忙吗?
谢谢!
如何检索价格?
【问题讨论】:
标签: python selenium web-scraping xpath scrapy
您的问题不是 xpath,而是使用 XHR 检索价格。
如果你使用 scrapy sheel 并输入 view(response) 你可以看到没有生成价格:
然后用这个网址刮价格:
def parse(self, response):
import re
price_url = 'https://www.asos.com' + re.search(r'window.asos.pdp.config.stockPriceApiUrl = \'(.+)\'', response.text).group(1)
yield scrapy.Request(url=price_url,
method='GET',
callback=self.parse_price,
headers=self.headers)
def parse_price(self, response):
import json
jsonresponse = json.loads(response.text)
...............
...............
...............
我提供的标头无法解决 403 错误,但也许你会有更多的运气。
编辑:
为了从 json 文件中获取价格,实际上不需要 json.loads
def parse_price(self, response):
jsonresponse = response.json()[0]
price = jsonresponse['productPrice']['current']['text']
# You can also use jsonresponse.get() if you prefer
print(price)
输出:
£10.00
【讨论】:
您尝试过的这段代码:
price' :response.xpath('//*[contains(@class, "current-price")]').get()
看起来你的框架有自己的书面方法,但在本机 Selenium-Python 绑定中我会这样做:-
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 20)
print(wait.until(EC.visibility_of_element_located((By.XPATH, "//*[contains(@class, "current-price")]/span"))).text)
【讨论】:
您使用的 XPath 返回 2 个不同的元素。试试下面的xpath获取物品的价格
driver.find_element_by_xpath("//span[@data-id='current-price']").text
更新:
price :response.xpath('//span[@data-id='current-price']').get()
【讨论】: