【问题标题】:lxml / xpath - limiting output [duplicate]lxml / xpath - 限制输出
【发布时间】:2016-09-29 08:06:57
【问题描述】:

我正在编写一个 Python 2.7 脚本来从网站中提取日期。代码如下:

from lxml import html, etree
from urllib2 import urlopen
import requests

url = 'http://www.cardiffdevils.com/fixtures/'
newtree = etree.HTML(urlopen(url).read())

for section in newtree.xpath('//div[@class="month"]'):
    print section.xpath('h3[1]/text()')
    print section.xpath('//td[@class="date"]/text()')

月份输出正确,但我试图将每个部分的打印日期限制为仅在相应的“月份”类中找到的日期;目前它会吐出在整个页面中找到的所有日期。任何指针将不胜感激!

【问题讨论】:

    标签: python xpath lxml


    【解决方案1】:

    以句点 (.) 开始您的 XPath,使其相对于上下文元素:

    print section.xpath('.//td[@class="date"]/text()')
    

    关于这个问题我回答的最后一个问题(不同的语言,不同的 XPath 处理器):Foreach not iterating through elements

    【讨论】:

    • 你是个学者,而且(我认为)是个绅士,这正是我所需要的。谢谢!
    猜你喜欢
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-17
    • 2012-09-29
    • 2011-07-17
    • 2016-03-06
    • 1970-01-01
    相关资源
    最近更新 更多