【问题标题】:Getting parent tag id with lxml使用 lxml 获取父标签 ID
【发布时间】:2015-02-15 07:08:35
【问题描述】:

我正在尝试抓取一个虚拟网站并获取我正在搜索的网站的父标签。这是我正在搜索的代码的结构:

<div id='veg1'>
    <div class='veg-icon icon'></div>
</div>

<div id='veg2'>
</div>    

这是我的 python 脚本:

from lxml import html
import requests

req = requests.get('https://mysite.com')
vegTree = html.fromstring(req.text)
veg = vegTree.xpath('//div[div[@class="veg-icon vegIco"]]/id')

打印 veg 时,我得到一个空列表,但我希望得到 veg1。因为我没有收到错误,所以我不确定出了什么问题。正如我在上一个问题中所做的那样,并遵循了该语法。见lxml: get element with a particular child element?

【问题讨论】:

    标签: python xpath web-scraping lxml lxml.html


    【解决方案1】:

    您的 xpath 中很少有问题:

    • 您正在检查类veg-icon vegIco,而在HTML 中,子div 具有veg-icon icon
    • 属性前面带有@@id,而不是id

    固定版本:

    //div[div[@class="veg-icon icon"]]/@id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-13
      相关资源
      最近更新 更多