【问题标题】:python xpath returns empty listpython xpath返回空列表
【发布时间】:2018-01-27 05:43:02
【问题描述】:

以下代码返回一个空列表

import requests
from bs4 import BeautifulSoup
from lxml import html

YrlyURL=str("http://www.moneycontrol.com/financials/20microns/balance-sheetVI/2M#2M")
page3 = requests.get(YrlyURL, timeout=5)
soup3 = BeautifulSoup(page3.content, "lxml")
tree2 = html.fromstring(page3.content)
yr1 = tree2.xpath('//*[@id="mc_mainWrapper"]/div[3]/div[2]/div[3]/div[2]/div[2]/div[2]/div[1]/table[2]/tbody/tr[1]/td[2]')
print(yr1)

我需要 yr1 才能返回“3 月 17 日”,但我无法找到解决方案。请帮助我了解我做错了什么以及我需要在哪里进行更正。

问候。

【问题讨论】:

    标签: python-3.x xpath


    【解决方案1】:

    此 xpath 将返回整列

    '//table[@class="table4"]/tr/td[count(//table[@class="table4" and ./tr/td[.="Mar 17"]]/preceding-sibling::tr)+2]'

    <td class="detb" align="right">Mar 17</td> <td class="det" align="right">12 mths</td> <td class="detb" align="right"></td> <td class="detb" align="right"></td> <td class="det" align="right">17.64</td> <td class="hed" align="right">17.64</td> <td class="det" align="right">79.08</td> <td class="hed" align="right">79.08</td> <!-- more tds -->

    基于this question

    【讨论】:

    • 感谢 Luis 的帮助,但我需要知道为什么我自己的代码会失败并返回一个空列表。
    • 我建议将 html 保存到一个文件中,并使用 xmllint 或其他工具在命令行上调试您自己的 xpath,以便您首先确保您的 xpath 正常工作。顺便说一句,您的 xpath 类似于从浏览器开发工具中获取的那些,它们是通用的,并不总是适合代码。
    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    相关资源
    最近更新 更多