从检查器复制的xpath返回错误的结果

时间:2018-05-31 02:34:04

标签: python selenium web-scraping

我使用配置了chrome的selenium webdriver,并希望从雅虎财务中榨取价格。示例页面是:https://finance.yahoo.com/quote/0001.KL

我已经在Chrome浏览器中打开了示例页面,并使用检查器导航到页面上突出显示价格的位置,并使用检查器的复制xpath在我的python脚本中使用。 enter image description here

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%)']

这似乎是来自下一个跨度(变化和百分比变化)的信息,而不是价格。任何关于这种好奇行为的见解都将受到赞赏。对替代方法的任何建议也会带来快乐。

2 个答案:

答案 0 :(得分:1)

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

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

这会产生['0.36']

的正确输出

答案 1 :(得分:0)

这是另一种在没有硬编码索引的情况下可以实现相同输出的方法:

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