使用lxml从html中提取属性

问题描述 投票:0回答:3

我使用

lxml
从 html 页面检索标签的属性。 html 页面的格式如下:

<div class="my_div">
    <a href="/foobar">
        <img src="my_img.png">
    </a>
</div>

我用来检索

<a>
标签内的 url 以及同一
src
<img>
标签的
<div>
值的 python 脚本是这样的:

from lxml import html 

...
tree = html.fromstring(page.text)
for element in tree.xpath('//div[contains(@class, "my_div")]//a'):
    href = element.xpath('/@href')
    src = element.xpath('//img/@src')

为什么我拿不到琴弦?

python html lxml
3个回答
10
投票

0
投票

如果您将代码更改为:

from lxml import html 

...
tree = html.fromstring(page.text)
for element in tree.xpath('//div[contains(@class, "my_div")]//a'):
    href = element.items()[0][1]  #gives you the value corresponding to the key "href"
    src = element.xpath('//img/@src')[0]
    print(href, src)

你会得到你需要的。

lxml

文档提到了其中一些内容,但我觉得它缺少一些内容,您可能需要考虑使用交互式Python shell来研究
tree.xpath()
返回的实例的属性。或者你可以完全研究另一个解析器,例如 BeautifulSoup,它有非常好的示例和文档。只是分享...


0
投票

您没有获得想要的结果的原因是因为您试图从 NEXT 子节点而不是现有节点获取属性。

看这个:

from lxml import html

s = '''<div class="my_div">
    <a href="/foobar">
        <img src="my_img.png">
    </a>
</div>'''

tree = html.fromstring(s)

# when you do path... //a, you are ALREADY at 'a' node
for el in tree.xpath('//div[contains(@class, "my_div")]//a'):
    # you were trying to get next children /@href, which doesn't exist
    print el.xpath('@href') # you should instead access the existing node's 
    print el.xpath('img/@src') # same here, not /img/@src ...

['/foobar']
['my_img.png']

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.