【问题标题】:How to find and select a table in html code with xpath [closed]如何使用 xpath 在 html 代码中查找和选择表格 [关闭]
【发布时间】:2013-08-04 07:25:11
【问题描述】:

我是 python 和 xpath 的新手, 我有一个这样的html代码:

<a name="hello"></a>
<h3>hello</h3>
<table />

<a name="impact"></a>
<h3>Impact</h3>
<table cellspacing="0" cellpadding="0" border="0" class="wrapper-table"><tr> <td><p>An     unauthenticated attacker using a specifically crafted payload may be able to trick the Ruby on Rails backend into executing arbitrary code.</p></td></tr></table>

我想将整个表格及其所有标签和文本以及...保存在一个字符串中。 我想要影响标题之后的表格标签。

【问题讨论】:

    标签: xpath python-2.7 lxml


    【解决方案1】:

    使用

    tables = root.xpath('.//table[preceding-sibling::h3[text()="Impact"]]')
    

    tables = root.xpath('.//h3[text()="Impact"]/following-sibling::table')
    

    tables = root.cssselect('h3:contains(Impact) ~ table')
    

    完整的解决方案

    root = tree.getroot()
    tables = root.xpath('.//h3[text()="Impact"]/following-sibling::table')
    for table in tables:
        print str
    

    【讨论】:

    • :谢谢您的回复,但我还是不知道如何将表格保存在字符串中!
    • @NiloofarKhalilian, lxml.html.tostring(root) 会给你 html 字符串。
    • 我需要这个字符串 str=

      未经身份验证的使用特制有效载荷的攻击者可能能够欺骗 Ruby on Rails 后端执行任意代码。

      我怎样才能得到这个结果?
    • @NiloofarKhalilian,你看我的评论了吗? :(
    • 是的,我读过它,但我对 python 很陌生。这是我的代码:root=tree.getroot() tables = root.xpath('.//h3[text()=" Impact"]/following-sibling::table') str=etree.tostring(tables) print str 但我得到这个错误:Type 'list' cannot be serialized
    猜你喜欢
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    相关资源
    最近更新 更多