【问题标题】:How to get all html elements with id equal to `constant_text-something_changed`?如何获取 id 等于 `constant_text-something_changed` 的所有 html 元素?
【发布时间】:2014-05-26 12:51:11
【问题描述】:

我正在尝试使用 lxml 解析 html,如下所示:

<tr id="element-36a07b7" class=" " ... data-date="2014-05-25">
    <td>2014-05-25</td>
    <td>Wikipedia (<a href="http://example.com/36a07b7" title="Wikipedia search">link</a>)</td>
    <td>Yandex (<a href="http://ya.ru/36a07b7" title="Yandex search">link</a>)</td>
    <td title="what I am looking for">another needed info<span class="small">(<a href="http://example.com">info 3</a>)</span>
    </td>
    <td class="result">1</td>
    <td class="result">2</td>
    <td class="result">3</td>
    ...
</tr>

并希望获取 id 等于 element-... 的所有元素并从那里提取 36a07b7data-datewhat I am looking foranother needed infoinfo 3

首先,我正在尝试获取所有element-s:

elements = t.find('//*[@id="flight-"]')

如何在 id 名称中使用通配符?尝试使用*.*,但不起作用。

【问题讨论】:

    标签: python html parsing python-2.7 lxml


    【解决方案1】:

    使用starts-with函数:

    import lxml.html
    
    root = lxml.html.fromstring('''
    <table>
    <tr id="element-36a07b7" class=" "  data-date="2014-05-25">
        <td>2014-05-25</td>
        <td>Wikipedia (<a href="http://example.com/36a07b7" title="Wikipedia search">link</a>)</td>
        <td>Yandex (<a href="http://ya.ru/36a07b7" title="Yandex search">link</a>)</td>
        <td title="what I am looking for">another needed info<span class="small">(<a href="http://example.com">info 3</a>)</span>
        </td>
        <td class="result">1</td>
        <td class="result">2</td>
        <td class="result">3</td>
        ...
    </tr>
    </table>
    ''')
    
    tr_list = root.xpath('//*[starts-with(@id, "element-")]')
    for tr in tr_list:
        print tr.get('id').split('-')[1]
        print tr.get('data-date')
    

    输出:

    36a07b7
    2014-05-25
    

    或者,您可以使用 css 选择器,使用 cssselect 方法:

    tr_list = root.cssselect('[id^=element-]')
    

    【讨论】:

    • 非常感谢,假的!如何获取tr 的子元素?假设我是否需要获得第 4 个td 元素?
    • @LA_,XPath://*[starts-with(@id, "element-")]/td[4]
    • @LA_,CSS 选择器:[id^=element-]&gt;td:nth-child(4)
    • 谢谢,假的。我想了解如何在循环中做到这一点,例如for tr in tr_list: print tr.get('/td[4]')
    • @LA_、print tr.find('td[4]')print tr.find('./td[4]')
    猜你喜欢
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 2019-01-11
    • 2016-04-13
    • 2016-07-27
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    相关资源
    最近更新 更多