【问题标题】:Strip information from xpath?从 xpath 中剥离信息?
【发布时间】:2016-09-01 20:41:28
【问题描述】:

我使用以下代码行从网页中获取 CVE id:

  project.cve_information = "".join(xpath_parse(tree, '//div[@id="references"]/a/text()')).split()

但是,问题是:

            <div id='references'>
            <b>References:</b>
            <a href='https://access.redhat.com/security/cve/CVE-2011-3256' target='_blank'>CVE-2011-3256&nbsp;<i class='icon-external-link'></i></a>
            <a href='https://rhn.redhat.com/errata/RHSA-2011-1402.html' target='_blank'>RHSA-2011-1402&nbsp;<i class='icon-external-link'></i></a><br />
        </div>

参考:CVE-xxxx-xxxx RHSA-xxxx-xxxx

如何避免 RHSA 和此类条目被解析?我只想要 CVE-xxxx-xxxx 值。我用它来提交这样的表单:

          "form[CVEID]" : ",".join(self.cve_information) if self.cve_information else "GENERIC-MAP-NOMATCH",

此表单仅对 CVE 值和错误输出执行验证,因为我的代码往往包含 RHSA 值。

【问题讨论】:

    标签: python python-2.7 xpath html-parsing


    【解决方案1】:

    你可以使用包含

    h = """ <div id='references'>
                <b>References:</b>
                <a href='https://access.redhat.com/security/cve/CVE-2011-3256' target='_blank'>CVE-2011-3256&nbsp;<i class='icon-external-link'></i></a>
                <a href='https://rhn.redhat.com/errata/RHSA-2011-1402.html' target='_blank'>RHSA-2011-1402&nbsp;<i class='icon-external-link'></i></a><br />
            </div>"""
    
    from lxml import html
    
    xml = html.fromstring(h)
    
    urls = xml.xpath('//div[@id="references"]/a[contains(@href, "CVE")]/@href')
    

    或者如果你想忽略 RHSA 的 href,你可以使用 not contains

    urls = xml.xpath('//div[@id="references"]/a[not(contains(@href, "RHSA"))]/@href')
    

    两者都会给你:

     ['https://access.redhat.com/security/cve/CVE-2011-3256']
    

    【讨论】:

    • 嗯,我想我没有正确解释我的问题。我正在使用 xpath 表达式来解析“引用”字段。然后我在其他地方使用“CVE-xxxx-xxxx”ID,这样它就可以是web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-xxxx-xxxx。使用当前的解决方案,我得到 - 警告:无法找到有关 CVE CVE-2011-3256 的信息 - CVE-2011-3256 前面有一个额外的“CVE”
    • 你想要CVE-2011-3256吗?如果它们总是在最后,只需在/ 上进行 rsplit 并提取,如果它们可以在任何地方,那么您需要正则表达式或拆分并使用 str.strartswith 找到您想要的子字符串
    • 将 xpath 从 /@href 更改为 /text()
    • 太棒了!谢谢。只是对其进行了更多编辑以获得我想要的内容。
    猜你喜欢
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    相关资源
    最近更新 更多