【问题标题】:xpath copied from inspector returns wrong results从检查器复制的 xpath 返回错误的结果
【发布时间】:2018-05-31 02:34:04
【问题描述】:

我正在使用配置了 chrome 的 selenium webdriver,并希望从 Yahoo Finance 获取价格。示例页面是:https://finance.yahoo.com/quote/0001.KL

我在 chrome 浏览器中打开了示例页面,并使用检查器导航到页面上突出显示价格的位置,并使用检查器的副本 xpath 在我的 python 脚本中使用。

import os
from lxml import html
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent
ua = UserAgent()

def yahoo_scrape_one(kl_stock_id):
    ''' function to scrape yahoo finance for a single KLSE stock returns dict'''        
    user_agent = ua.random
    chrome_driver = os.getcwd() + '/chromedriver'
    chrome_options = Options()
    chrome_options.add_argument('user-agent={user_agent}')
    chrome_options.add_argument('--headless')
    driver = webdriver.Chrome(chrome_options=chrome_options,
                      executable_path=chrome_driver)
    prefix = 'https://finance.yahoo.com/quote/'
    suffix = '.KL'
    url = prefix + kl_stock_id + suffix
    driver.get(url)
    tree = html.fromstring(driver.page_source)
    price = tree.xpath('//*[@id="quote-header-info"]/div[3]/div/div/span[1]/text()')
    print(price)

test_stock = "0001"
yahoo_scrape_one(test_stock)

打印输出是

['+0.01 (+1.41%)']

这似乎是来自下一个跨度(变化和百分比变化)的信息,而不是价格。对这种奇怪行为的任何见解将不胜感激。任何关于替代方法的建议也会让人高兴。

【问题讨论】:

  • 我无法复制您的问题。使用相同的 XPath 时,我得到 ['0.36'] 作为输出。
  • @MihaiChelaru 我已经更新了我的代码片段以包含导入,但我仍然没有得到价格:['0.36'] 你在使用 selenium 的 html.fromstring 方法吗?
  • 如果您遇到问题,您不能只从父 div 中获取所有文本,然后删除第一行文本之后的所有内容吗?

标签: python selenium web-scraping


【解决方案1】:

运行您的实际脚本后,我得到了与您报告的相同的“错误”输出。但是,我随后注释掉了 headless 选项并再次运行驱动程序,检查实际 Selenium 浏览器实例中的元素,发现该元素的 XPath 在脚本生成的页面上有所不同。请改用以下代码行:

price = tree.xpath('//*[@id="quote-header-info"]/div[3]/div/span/text()')

这会产生['0.36']的正确输出

【讨论】:

  • 好的,谢谢。我从这次经历中得出的结论是:检查员的 XPath 副本让您了解附近情况,但可能会给出错误的结果。如果需要 div 中的第一个 span 实例,请使用 .../div/span/text() 但要获取第二个实例,请使用 .../div./span[1]/text()
【解决方案2】:

这是另一种无需硬编码索引即可实现相同输出的方法:

price = tree.xpath("//*[@id='quote-market-notice']/../span")[0].text

【讨论】:

    猜你喜欢
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 2013-11-15
    • 1970-01-01
    相关资源
    最近更新 更多