【问题标题】:lxml requests on repl.itrepl.it 上的 lxml 请求
【发布时间】:2016-12-15 11:19:58
【问题描述】:

我正在Replit 上尝试 lxml 请求,但我不明白为什么它不起作用。该程序不会停止运行,直到最大重试次数,我得到这个错误:

Traceback(最近一次调用最后一次): 文件“python”,第 6 行,在 requests.exceptions.ConnectionError: HTTPConnectionPool(host='www.presidency.ucsb.edu', port=80): url: /ws/index.php?pid=29400.html (由 NewConnectionError(':建立新连接失败:[Errno -2] Name or service not known',))

我的代码很简单:

from lxml import html
import requests

url = 'http://www.presidency.ucsb.edu/ws/index.php?pid=29400.html'

r = requests.get(url)
tree = html.fromstring(r.content)

text = tree.xpath('//span[@class="displaytext"]/text()')

print(text)

我怎样才能让它运行?我正在尝试获取位于“displaytext”跨度类中的该网站的内容。我一直在使用this Python guide 作为参考。

Python 3.5 版

【问题讨论】:

  • 当我运行你的代码时,我确实得到了输出:>>> print text ["HOWARD K. SMITH, MODERATOR: Good evening. The television and radio stations of the United States and their affiliated stations are proud to provide facilities for a discussion of issues in the current political campaign by the two major candidates for the presidency. The candidates need no introduction. The Republican candidate, ...etc... 你是否通过 pip 安装了请求模块?蟒蛇版本? (我的是 2.7)
  • ps:我直接在 python 中工作。 repl.it 不允许我导入请求
  • 所以问题在于 repl.it 中的拉取请求。谢谢:)

标签: python web-scraping lxml


【解决方案1】:

我是 Repl.it 的一名工程师,这是我们平台的一个限制。我们目前不允许传出网络请求。

【讨论】:

  • 我能问一下为什么吗?你打算有一天以某种方式支持它吗?
  • 还有其他支持外发请求的在线IDE吗?
  • @AlanPallath,python 任何地方都可以。但是你需要付费/注册,但是相对便宜。
【解决方案2】:

切换到回答,因为它可以让我更好地安排事情。

查看您的目标网站的 html。使用此命令,您只选择 1 个特定标签:

text = tree.xpath('//span[@class="displaytext"]/text()')

指向具有“displaytext”类的特定范围

您可以将代码更改为:

text = tree.xpath('//span[@class="displaytext"]/..')
for element in text[0]:
    print element

这将选择类为“displaytext”的跨度,然后选择该跨度的父级。在 for 循环中,您将打印该父级的所有子级。

现在它也显示了真正的问题:段落元素不在该列表中。抱歉,不知道答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多