2016-11-30 98 views
1

这是互联网上的文本文件(http)http://hughchalmers.com/example.txt。我将如何在Python 2中打印?通过互联网在python上阅读文本文件

人们都说,这是一个重复,我想说,这是不是重复,我发现其他脚本给错误412

+0

像'urllib'或'requests'这样的模块可以提供帮助。 –

+0

我似乎无法找出它们中的任何一个在这方面的工作。我并没有真正做Python,我更像是一个Web开发人员。 –

+3

可能的重复[在Python中,给定一个文本文件的URL,什么是最简单的方式来读取文本文件的内容?](http://stackoverflow.com/questions/1393324/in-python-given- a-url-to-a-text-file-what-is-the-simple-way-to-read-the-cont) – zondo

回答

3
>>> 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' 
+0

谢谢,完美的工作。将在3m –

+0

接受答案有趣的用户代理。 –

0

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

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

我已经添加了用户代理标题,所以这应该与您的服务器现在一起工作。 –