【发布时间】:2017-02-13 16:50:47
【问题描述】:
其实情况要复杂一点。
我正在尝试从此示例 html 中获取数据:
<li itemprop="itemListElement">
<h4>
<a href="/one" title="page one">one</a>
</h4>
</li>
<li itemprop="itemListElement">
<h4>
<a href="/two" title="page two">two</a>
</h4>
</li>
<li itemprop="itemListElement">
<h4>
<a href="/three" title="page three">three</a>
</h4>
</li>
<li itemprop="itemListElement">
<h4>
<a href="/four" title="page four">four</a>
</h4>
</li>
目前,我正在使用带有urllib 和lxml 的Python 3。
由于某种原因,以下代码无法按预期工作(请阅读 cmets)
scan = []
example_url = "path/to/html"
page = html.fromstring(urllib.request.urlopen(example_url).read())
# Extracting the li elements from the html
for item in page.xpath("//li[@itemprop='itemListElement']"):
scan.append(item)
# At this point, the list 'scan' length is 4 (Nothing wrong)
for list_item in scan:
# This is supposed to print '1' since there's only one match
# Yet, this actually prints '4' (This is wrong)
print(len(list_item.xpath("//h4/a")))
如您所见,第一步是提取 4 个li 元素并将它们附加到一个列表中,然后扫描每个li 元素以查找a 元素,但问题是每个li scan 中的元素其实就是这四个元素。
...或者我是这么认为的。
通过快速调试,我发现scan 列表正确包含四个li 元素,因此我得出了一个可能的结论:上面提到的for 循环有问题。
for list_item in scan:
# This is supposed to print '1' since there's only one match
# Yet, this actually prints '4' (This is wrong)
print(len(list_item.xpath("//h4/a")))
# Something is wrong here...
唯一真正的问题是我无法确定错误。是什么原因造成的?
PS:我知道,有一种更简单的方法可以从列表中获取 a 元素,但这只是一个示例 html,真正的包含更多...的东西。
【问题讨论】:
标签: python-3.x loops xpath lxml urllib