【问题标题】:How to use Xpath to return the content?如何使用 Xpath 返回内容?
【发布时间】:2020-06-11 02:35:08
【问题描述】:
<tr>
    <td width="120" align="right" class="tit">Bank:</td>
    <td><span style="text-decoration: underline;color: #0066ff;cursor: pointer"  onclick="_search('ad','2016.11.22');">2016.11.22</span></td>
</tr>
<tr>
    <td width="120" align="right" class="tit">Shop:</td>
    <td>CN108084067B</td>
</tr>

如何使用 Xpath 来获得名称“Shop”?我使用下面的代码不起作用。

number3 = html.xpath('//tr[contains(text(),"Bank")]/following-sibling::tr[1]/td/text()')[0]

【问题讨论】:

  • 你的问题不清楚:选择“Shop”的依据是什么?是不是因为在第二个&lt;tr&gt;,第一个跟在“Bank”后面的,还有别的原因?

标签: python html xpath


【解决方案1】:

在 Selenium 中试试这个

driver.find_element_by_xpath('....xpath...').get_attribute('innerHTML')

【讨论】:

    【解决方案2】:

    如果它必须是紧跟在“银行”之后的那个,那么你可以试试 '//td[contains(text(),"Bank")]//parent::tr//following-sibling::tr/td[contains(text(),"Shop")]'

    【讨论】:

    • "Shop" 有不同的值。这就是为什么需要建立价值不变的“银行”
    【解决方案3】:

    只需修复您的 XPath:

    //tr[contains(.,"Bank")]/following-sibling::tr[1]/td[1]/text()
    

    代码:

    data = """HTML
    <table>
    <tr>
        <td width="120" align="right" class="tit">Bank:</td>
        <td><span style="text-decoration: underline;color: #0066ff;cursor: pointer"  onclick="_search('ad','2016.11.22');">2016.11.22</span></td>
    </tr>
    <tr>
        <td width="120" align="right" class="tit">Shop:</td>
        <td>CN108084067B</td>
    </tr>
    </table>
    HTML"""
    
    import lxml.html
    tree = lxml.html.fromstring(data)
    print (tree.xpath('//tr[contains(.,"Bank")]/following-sibling::tr[1]/td[1]/text()'))
    

    输出:

    ['Shop:']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-15
      • 2017-07-24
      • 1970-01-01
      • 2013-03-04
      • 1970-01-01
      • 2013-04-07
      • 2011-01-20
      • 1970-01-01
      相关资源
      最近更新 更多