【问题标题】:Read text file over internet on python在 python 上通过 Internet 读取文本文件
【发布时间】:2016-11-30 20:04:51
【问题描述】:

这是 Internet (http) http://hughchalmers.com/example.txt 上的一个文本文件。我将如何在 Python 2 中打印它?

人们说这是重复的,我想说它不是重复的,我发现的任何其他脚本都给出了错误 412。

【问题讨论】:

标签: python python-2.x


【解决方案1】:
>>> from urllib2 import Request, urlopen
>>> url = 'http://hughchalmers.com/example.txt'
>>> urlopen(Request(url=url, headers={'User-Agent': "hey, it's wim"})).read()
'Exmaple Text'

【讨论】:

  • 谢谢,完美运行。将在 3m 后接受作为答案
  • 有趣的用户代理。
【解决方案2】:

您可以使用requests。他们的第一个例子展示了如何:

import requests
r = requests.get('http://hughchalmers.com/example.txt', headers={'user-agent': 'hugh'})
r.text

【讨论】:

  • 我已经添加了用户代理标头,所以现在应该可以在您的服务器上使用了。
猜你喜欢
  • 2017-10-26
  • 1970-01-01
  • 2012-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-28
  • 2021-12-22
  • 2021-07-10
相关资源
最近更新 更多