如何使用Python读取URL的内容?
当我将其粘贴到浏览器中时,以下方法起作用:
http://www.somesite.com/details.pl?urn=2344
但是,当我尝试使用Python读取URL时,没有任何反应:
link = 'http://www.somesite.com/details.pl?urn=2344'
f = urllib.urlopen(link)
myfile = f.readline()
print myfile
我需要对URL进行编码,还是没有看到什么?
-
要回答您的问题:
import urllib link = "http://www.somesite.com/details.pl?urn=2344" f = urllib.urlopen(link) myfile = f.read() print(myfile)
您需要
read()
,而不是readline()
编辑(2018-06-25):自Python
3起,旧版urllib.urlopen()
被替换为urllib.request.urlopen()
(有关详细信息,请参阅https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen中的注释)
。或者,只需在此处获取此库:http :
//docs.python-requests.org/en/latest/并认真使用它即可:)import requests link = "http://www.somesite.com/details.pl?urn=2344" f = requests.get(link) print(f.text)