【问题标题】:Xpath returns nullXpath 返回 null
【发布时间】:2021-07-31 23:11:09
【问题描述】:

我要刮这个页面的价格:https://www.asos.com/monki/monki-lisa-cropped-vest-top-with-ruched-side-in-black/prd/23590636?colourwayid=60495910&cid=2623

但是它总是返回 null:

我的代码:

'price' :response.xpath('//*[contains(@class, "current-price")]').get()

有人可以帮忙吗?

谢谢!

使用 XHR 提取时:

如何检索价格?

【问题讨论】:

    标签: python selenium web-scraping xpath scrapy


    【解决方案1】:

    您的问题不是 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
    

    【讨论】:

    • 嗨,我尝试了使用 json 的方式,并在我的问题中得到了更新的结果。你能告诉我现在如何从 json 结果中检索价格吗?谢谢!
    • @Fazlul 真的吗?怎么样??
    【解决方案2】:

    您尝试过的这段代码:

    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)
    

    【讨论】:

    • 我已经更新了我的问题。你能告诉我如何将它添加到我的收益中吗?我是新手。谢谢!
    【解决方案3】:

    您使用的 XPath 返回 2 个不同的元素。试试下面的xpath获取物品的价格

    driver.find_element_by_xpath("//span[@data-id='current-price']").text
    

    更新:

    price :response.xpath('//span[@data-id='current-price']').get()
    

    【讨论】:

    • 像这样: def parse(self, response): yield{ 'price': driver.find_element_by_xpath("//span[@data-id='current-price']").text } ------不工作:(
    • 错误是什么?更新了我的代码。试试吧
    • 不幸的是仍然为空。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 2015-02-27
    • 2016-11-01
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    相关资源
    最近更新 更多