对于下面的代码,我需要分别获得日期和它们的times+hrefs+formats+.(未显示)。
<div class="showtimes">
<h2>The Little Prince</h2>
<div class="poster" data-poster-url="http://www.test.com">
<img src="http://www.test.com">
</div>
<div class="showstimes">
<div class="date">9 December, Wednesday</div>
<span class="show-time techno-3d">
<a href="http://www.test.com" class="link">12:30</a>
<span class="show-format">3D</span>
</span>
<span class="show-time techno-3d">
<a href="http://www.test.com" class="link">15:30</a>
<span class="show-format">3D</span>
</span>
<span class="show-time techno-3d">
<a href="http://www.test.com" class="link">18:30</a>
<span class="show-format">3D</span>
</span>
<div class="date">10 December, Thursday</div>
<span class="show-time techno-2d">
<a href="http://www.test.com" class="link">12:30</a>
<span class="show-format">2D</span>
</span>
<span class="show-time techno-3d">
<a href="http://www.test.com" class="link">15:30</a>
<span class="show-format">3D</span>
</span>
</div>
</div>为此,我使用以下代码(python)。
for dates in movie.xpath('.//div[@class="showstimes"]/div[@class="date"]'):
date = dates.xpath('.//text()')[0]
# for times in dates.xpath('//following-sibling::span[1 = count(preceding-sibling::div[1] | (.//div[@class="date"])[1])]'):
# for times in dates.xpath('//following-sibling::span[contains(@class,"show-time")]'):
# for times in dates.xpath('.//../span[contains(@class,"show-time")]'):
# for times in dates.xpath('//following-sibling::span[preceding-sibling::div[1][.="date"]]'):
time = times.xpath('.//a/text()')[0]
url = times.xpath('.//a/@href')[0]
format_type = times.xpath('.//span[@class="show-format"]/text()')[0]获得日期并不是一个问题,但我有一个问题,如何获得其余的信息,分别为特定日期。尝试了许多不同的方法-没有运气(在评论中,其中一些)。当我需要的节点位于另一个节点下(在同一级别上?)时,我无法找到处理这种情况的方法。在这种情况下:
-> div Date1
-> span Time1
-> span href1
-> span Format1
-> span Time2
-> span href2
-> span Format2
-> span Time3
-> span href3
-> span Format3
-> div Date2
-> span Time1
-> span href1
-> span Format1
# etc etc发布于 2015-12-08 23:04:27
事实证明,lxml支持从XPath表达式引用python变量,这在本例中非常有用,即对于每个div date,您可以得到以下同级span,最近的同级div date是当前的div date,其中对当前div date的引用存储在python变量dates中:
for dates in movie.xpath('.//div[@class="showstimes"]/div[@class="date"]'):
date = dates.xpath('normalize-space()')
for times in dates.xpath('following-sibling::span[preceding-sibling::div[1]=$current]', current=dates):
time = times.xpath('a/text()')[0]
url = times.xpath('a/@href')[0]
format_type = times.xpath('span/text()')[0]
print date, time, url, format_type输出:
'9 December, Wednesday', '12:30', 'http://www.test.com', '3D'
'9 December, Wednesday', '15:30', 'http://www.test.com', '3D'
'9 December, Wednesday', '18:30', 'http://www.test.com', '3D'
'10 December, Thursday', '12:30', 'http://www.test.com', '2D'
'10 December, Thursday', '15:30', 'http://www.test.com', '3D'参考资料:
https://stackoverflow.com/questions/34166948
复制相似问题