แก้ไข 09/2016: ใน Python 3 ขึ้นไปให้ใช้urllib.requestแทน urllib2
จริงๆแล้ววิธีที่ง่ายที่สุดคือ:
import urllib2 # the lib that handles the url stuff
data = urllib2.urlopen(target_url) # it's a file like object and works just like a file
for line in data: # files are iterable
print line
คุณไม่จำเป็นต้องมี "readlines" ตามที่ Will แนะนำ คุณสามารถย่อให้สั้นลงเป็น: *
import urllib2
for line in urllib2.urlopen(target_url):
print line
แต่จำไว้ใน Python ความสามารถในการอ่านเป็นเรื่องสำคัญ
อย่างไรก็ตามนี่เป็นวิธีที่ง่ายที่สุด แต่ไม่ใช่วิธีที่ปลอดภัยเนื่องจากเวลาส่วนใหญ่ในการเขียนโปรแกรมเครือข่ายคุณจะไม่รู้ว่าปริมาณข้อมูลที่คาดหวังจะได้รับการเคารพหรือไม่ ดังนั้นโดยทั่วไปคุณควรอ่านข้อมูลในปริมาณที่คงที่และสมเหตุสมผลสิ่งที่คุณรู้ว่าเพียงพอสำหรับข้อมูลที่คุณคาดหวัง แต่จะป้องกันไม่ให้สคริปต์ของคุณท่วม:
import urllib2
data = urllib2.urlopen("http://www.google.com").read(20000) # read only 20 000 chars
data = data.split("\n") # then split it into lines
for line in data:
print line
* ตัวอย่างที่สองใน Python 3:
import urllib.request # the lib that handles the url stuff
for line in urllib.request.urlopen(target_url):
print(line.decode('utf-8')) #utf-8 or iso8859-1 or whatever the page encoding scheme is