我正在尝试从 td 标签的第一个子标签中提取 foo 类的 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 而不是进行迭代会更有效,但不确定如何构造它。
谢谢。
最佳答案
是的,您可以通过从每个 td
内的 a
标记获取 @href
来简化它:
return tree.xpath('//td[@class="foo"]/a/@href')
关于python - lxml - 根据父类获取子类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26691515/