【问题标题】:Can't create an xpath capable of meeting certain condition无法创建能够满足特定条件的 xpath
【发布时间】:2018-11-17 07:11:30
【问题描述】:

我创建了一个脚本,它能够从网页中提取tableFile 类下可用的以.html 扩展名结尾的链接。该脚本可以完成它的工作。然而,我此时的意图是只获取那些在其类型字段中具有EX-.html 链接。我正在寻找任何纯 xpath 解决方案(不使用 .getparent() 或其他东西)。

Link to that site

到目前为止我尝试过的脚本:

import requests
from lxml.html import fromstring

res = requests.get("https://www.sec.gov/Archives/edgar/data/1085596/000146970918000185/0001469709-18-000185-index.htm")
root = fromstring(res.text)

for item in root.xpath('//table[contains(@summary,"Document")]//td[@scope="row"]/a/@href'):
    if ".htm" in item:
        print(item)

当我尝试使用以下方法使链接满足上述条件时,出现错误:

for item in root.xpath('//table[contains(@summary,"Document")]//td[@scope="row"]/a/@href'):
    if ".htm" in item and "EX" in item.xpath("..//following-sibling::td/text"):
        print(item)

我得到的错误:

if ".htm" in item and "EX" in item.xpath("..//following-sibling::td/text"):
AttributeError: 'lxml.etree._ElementUnicodeResult' object has no attribute 'xpath'

文件是这样的:

【问题讨论】:

    标签: python python-3.x xpath web-scraping


    【解决方案1】:

    如果您需要纯 XPath 解决方案,可以使用以下方法:

    import requests
    from lxml.html import fromstring
    
    res = requests.get("https://www.sec.gov/Archives/edgar/data/1085596/000146970918000185/0001469709-18-000185-index.htm")
    root = fromstring(res.text)
    for item in root.xpath('//table[contains(@summary,"Document")]//tr[td[starts-with(., "EX-")]]/td/a[contains(@href, ".htm")]/@href'):
        print(item)
    
    
    /Archives/edgar/data/1085596/000146970918000185/ex31_1apg.htm
    /Archives/edgar/data/1085596/000146970918000185/ex31_2apg.htm
    /Archives/edgar/data/1085596/000146970918000185/ex32_1apg.htm
    /Archives/edgar/data/1085596/000146970918000185/ex32_2apg.htm
    

    【讨论】:

    • 对@sir Andersson 延迟回复表示歉意。感谢您的有效解决方案。
    • 有什么方法可以使用.cssselect()@sir Andersson 做同样的事情吗?希望大家有空看看。
    • @robots.txt ,你可以试试[link.attrib['href'] for link in root.cssselect('table[summary*="Document"] td>a:contains("ex")[href*="htm"]')] ,但是CSS选择器没有那么灵活恕我直言,所以它和提供的XPath不一样
    【解决方案2】:

    看起来像你想要的:

    //td[following-sibling::td[starts-with(text(), "EX")]]/a[contains(@href, ".htm")]
    

    使用 xpath 有很多不同的方法可以做到这一点。 Css 可能要简单得多。

    【讨论】:

      【解决方案3】:

      这是一种使用数据框和熊猫的方法

      import pandas as pd
      tables = pd.read_html("https://www.sec.gov/Archives/edgar/data/1085596/000146970918000185/0001469709-18-000185-index.htm")
      base = "https://www.sec.gov/Archives/edgar/data/1085596/000146970918000185/"
      results = [base + row[1][2] for row in tables[0].iterrows() if row[1][2].endswith(('.htm', '.txt')) and str(row[1][3]).startswith('EX')]
      print(results)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-27
        • 2011-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-03
        相关资源
        最近更新 更多