【问题标题】:lxml - get attribute of child based on parent classlxml - 根据父类获取子类的属性
【发布时间】:2014-11-01 18:17:25
【问题描述】:

我正在尝试从类 foo 的 td 标记的第一个子项中提取 href。一个示例 DOM 是:

<td class="foo">
   <a href="www.foobar1.com"></a>
</td>
<td class="foo">
   <a href="www.foobar2.com"></a>
</td>

从这里我想得到["www.foobar1.com", "www.foobar2.com"]

到目前为止,我有以下内容:

import requests
from lxml import html

def get_hrefs(url):
    page = requests.get(url)
    tree = html.fromstring(page.text)
    td_elements = tree.xpath('//td[@class="foo"]')

    return [el.find("a").attrib["href"] for el in td_elements]

但是,我觉得扩展 xpath 而不是进行迭代会更有效,但不确定如何构造它。

谢谢。

【问题讨论】:

    标签: python html xpath lxml lxml.html


    【解决方案1】:

    是的,您可以通过从每个 td 内的 a 标记中获取 @href 来简化它:

    return tree.xpath('//td[@class="foo"]/a/@href')
    

    【讨论】:

    • 这是否只返回每个 td 的第一个孩子?我问是因为我得到了更多的href,然后那个类有td。
    • dom_tree.xpath('//td[@class="link"]/a[1]//@href') 似乎可以解决这种情况!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 2020-10-19
    • 1970-01-01
    相关资源
    最近更新 更多