【问题标题】:python tree.xpath return empty listpython tree.xpath 返回空列表
【发布时间】:2020-01-16 10:01:18
【问题描述】:

我很难弄清楚为什么下面代码中显示的 tree.xpath 方法会返回一个空列表。 在此示例中,我只是尝试在 yahoo Finance 中的“People also Watch”横幅下检索股票代码,这似乎很简单,但到目前为止还无法实现。

我正在从检查元素页面复制 xpath。也尝试过手动更改 xpath,例如删除“tbody”,但它也不起作用。 任何帮助将非常感激。谢谢你

import requests
from lxml import html


ticker = 'TSLA'
url = 'https://finance.yahoo.com/quote/'+str(ticker)+'?p='+str(ticker)
page = requests.get(url)
tree = html.fromstring(page.content)
tree.xpath('//*[@id="rec-by-symbol"]/table/tbody/tr[1]/td[1]/a')```




【问题讨论】:

    标签: python xpath web-scraping


    【解决方案1】:

    您正在尝试解析页面,该页面正在被浏览器渲染为 HTML 代码。如果您打开页面的源代码 - 您会看到,它有一个大脚本标签,其中包含所有要渲染的数据。

    你有两种方法来处理这种情况:

    1.渲染页面并在其中运行 XPathes。

    它是关于在浏览器中打开页面,从中获取渲染的 DOM 并运行 XPath。

    在这种情况下使用的最佳工具 - 带有某种 webdriver 的 selenium(通过 python 代码控制浏览器的工具)

    适合您情况的示例代码:

    from selenium import webdriver
    driver = webdriver.Chrome()
    
    ticker = 'TSLA'
    url = 'https://finance.yahoo.com/quote/'+str(ticker)+'?p='+str(ticker)
    driver.get(url)
    
    xpath = '//*[@id="rec-by-symbol"]/table/tbody/tr[1]/td[1]/a'
    found_nodes = driver.find_elements_by_xpath(xpath)
    
    for node in found_nodes:
        print(node.text)
    
    driver.close()
    driver.quit()
    

    但是您需要安装 selenium 并下载正确的驱动程序。对于我在示例中使用的 Chrome,它将是 chromedriver(您可以在此处获取:https://chromedriver.chromium.org/):

    pip install selenium
    

    2.将脚本解析为对象(尤其是节点 root.App.main)并使用它

    这种方式比较复杂,但不需要浏览器。

    工作流程:

    a. Download page via requests;
    b. Get script with target data (via regular expressions);
    c. load root.App.main as json Object (json.loads method);
    d. Find necessary nodes in Object.
    

    我不会为这种情况提供任何代码,因为它需要为您的任务编写几乎整个解析器。

    【讨论】:

      【解决方案2】:

      如果你不需要任何像 selenium 这样的副包,并且你只想使用 requests 和 lxml,就像我自己做的那样。我已经将 regex 用于此类事情:

      例如,您可以只查看 page.context 并从站点中找到一些您需要的 json 结构,例如:

      "NFLX":{"sourceInterval":15,"regularMarketOpen":{"raw":338.68,"fmt":"338.68"},"exchange":"NMS","regularMarketTime":{"raw":1579122001,"fmt":"4:00PM EST"},"fiftyTwoWeekRange":{"raw":"252.28 - 385.99","fmt":"252.28 - 385.99"},
      

      在这里你可以找到比 lxml 更多的信息,但它可能更难

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-10
        • 1970-01-01
        相关资源
        最近更新 更多