2016-09-29 54 views
0

我正在使用Python 2.7脚本从网站中提取日期。代码如下:lxml/xpath - 限制输出

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()') 

的几个月正在输出正确的,但我想限制打印的每一部分,只有那些相应的“月”类中发现的日期;目前它将所有日期发现在整个页面中。任何指针将不胜感激!

回答

0

与周期(.),使其相对于上下文元素开始您的XPath:

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

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

+0

你我是一个学者,(我认为)是一位绅士,这正是我所需要的。谢谢! –