【问题标题】:lxml cssselect - specific partlxml cssselect - 特定部分
【发布时间】:2019-09-13 13:07:10
【问题描述】:

我需要获取网页的翻译部分。

这是我的python代码:

import urllib.request

u = urllib.request.urlopen("https://docs.python-guide.org/writing/structure/#structure-of-the-repository")
data = u.read()

from lxml import html
information = html.document_fromstring(data)

for content in information.cssselect('ul li a'):
    print(content.text_content())

最后,我也得到了目录部分,我不知道如何过滤信息。

什么是达到此目的的正确方法?

我不得不说我从来没有使用过python,对此我的了解有限。

【问题讨论】:

  • 先找到所有ul,再用第二个得到li a

标签: python parsing css-selectors lxml


【解决方案1】:

你可以得到所有ul,然后用正确的一个得到li a

我发现第 6 个ul 有你的数据

for content in information.cssselect('ul')[6].cssselect('li a'):
    print(content.text_content())

结果

English
French
Chinese
Japanese
Korean
Filipino
Brazilian Portuguese

编辑:同样的使用xpath需要7而不是6,因为它从1开始计数而不是0

for content in information.xpath('(//ul)[7]/li/a'):
    print(content.text_content())

【讨论】:

  • 我从你那里学到了一些新东西。您的回答清晰而准确。非常感谢!!
猜你喜欢
  • 2011-06-22
  • 2011-08-01
  • 1970-01-01
  • 2011-10-15
  • 2011-05-26
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多