2013-02-28 19 views
41

下面的作品,當我將其粘貼在瀏覽器上:如何使用Python讀取URL的內容?

http://www.somesite.com/details.pl?urn=2344 

但是當我嘗試讀取URL使用Python什麼也沒有發生:

link = 'http://www.somesite.com/details.pl?urn=2344' 
f = urllib.urlopen(link)   
myfile = f.readline() 
print myfile 

我需要編碼的URL,或者是有我沒有看到的東西?

回答

86

要回答你的問題:

import urllib 

link = "http://www.somesite.com/details.pl?urn=2344" 
f = urllib.urlopen(link) 
myfile = f.read() 
print myfile 

您需要read(),不readline()

或者,只是讓這個庫的位置: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 
+0

感謝我改成了閱讀(),而該訣竅 – 2013-02-28 17:14:34

+0

@HelenNeely享受你的編程旅程 – woozyking 2013-02-28 17:51:11

+0

感謝鏈接到'請求'庫 - 像抽象那裏 – 2015-02-04 13:29:43

-1

URL應該是一個字符串:

import urllib 

link = "http://www.somesite.com/details.pl?urn=2344" 
f = urllib.urlopen(link)   
myfile = f.readline() 
print myfile 
+8

既有「和」在Python字符串 – Leons 2015-07-25 13:01:32

8

用與Python 2.X和Python 3.X作品的溶液利用了Python 2和3兼容性庫six的:

from six.moves.urllib.request import urlopen 
link = "http://www.somesite.com/details.pl?urn=2344" 
response = urlopen(link) 
content = response.read() 
print(content) 
0

我用下面的代碼:

import urllib 

def read_text(): 
     quotes = urllib.urlopen("https://s3.amazonaws.com/udacity-hosted-downloads/ud036/movie_quotes.txt") 
     contents_file = quotes.read() 
     print contents_file 

read_text() 
0

對於python3用戶,爲了節省時間,使用下面的代碼,

from urllib.request import urlopen 

link = "https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" 

f = urlopen(link) 
myfile = f.read() 
print (myfile) 

我知道有DIF不明確的線程錯誤:Name Error: urlopen is not defined,但認爲這可能會節省時間。

0

我們可以閱讀網站的HTML內容如下:。

from urllib.request import urlopen 
response = urlopen('http://google.com/') 
html = response.read() 
print(html)