Chỉnh sửa 09/2016: Trong Python 3 và UP Sử dụng urllib.request thay vì urllib2
Trên thực tế, cách đơn giản nhất là:
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
Bạn thậm chí không cần "đọc lại", như đã đề xuất. Bạn thậm chí có thể rút ngắn nó thành: *
import urllib2
for line in urllib2.urlopen[target_url]:
print line
Nhưng hãy nhớ trong Python, vấn đề dễ đọc.
Tuy nhiên, đây là cách đơn giản nhất nhưng không phải là cách an toàn vì hầu hết thời gian với lập trình mạng, bạn không biết liệu lượng dữ liệu mong đợi có được tôn trọng hay không. Vì vậy, bạn thường đọc tốt hơn một lượng dữ liệu cố định và hợp lý, một cái gì đó bạn biết là đủ cho dữ liệu bạn mong đợi nhưng sẽ ngăn chặn kịch bản của bạn bị ngập lụt:
import urllib2
data = urllib2.urlopen["//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
* Ví dụ thứ hai trong 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
- Cách đọc tệp văn bản từ URL trong Python.
- url = "//textfiles.com/adventure/Aencerse.txt".
- Tệp = urllib. lời yêu cầu. Urlopen [URL].
- Đối với dòng trong tập tin:.
- Phương pháp 3: Sử dụng urllib3.poolManager []
- & Nbsp; Lưu ý: Mã này nối một dòng trống [
$ pip install requests
2] vào đầu ra. - Sau đó, biến
$ pip install requests
9 tạo ra một đối tượngimport urllib.request import requests import urllib from urllib.request import urlopen import urllib3
0 tương tự như bên dưới. - & Nbsp; Lưu ý: Mã này nối một dòng trống [
$ pip install requests
2] vào đầu ra.
Cách đọc tệp văn bản từ URL trong Python.
url = "//textfiles.com/adventure/Aencerse.txt".
Tệp = urllib. lời yêu cầu. Urlopen [URL].
Đối với dòng trong tập tin:.
💬 Câu hỏi: Làm thế nào chúng ta sẽ viết mã Python để đọc một tệp văn bản từ URL?Question: How would we write Python code to read a text file from a URL?
Chúng tôi có thể hoàn thành nhiệm vụ này bằng một trong các tùy chọn sau:
- Phương pháp 1: Sử dụng
1: Useimport urllib2 for line in urllib2.urlopen[target_url]: print line
1import urllib2 for line in urllib2.urlopen[target_url]: print line
- Phương pháp 2: Sử dụng
2: Useimport urllib2 for line in urllib2.urlopen[target_url]: print line
2import urllib2 for line in urllib2.urlopen[target_url]: print line
- Phương pháp 3: Sử dụng
3: Useimport urllib2 for line in urllib2.urlopen[target_url]: print line
3import urllib2 for line in urllib2.urlopen[target_url]: print line
- Phương pháp 4: Sử dụng ________ 11.Read [n]: Use
1.read[n]import urllib2 for line in urllib2.urlopen[target_url]: print line
- Phương pháp 5: Sử dụng ________ 15 ________ 11.Read []: Use
5import urllib2 for line in urllib2.urlopen[target_url]: print line
1.read[]import urllib2 for line in urllib2.urlopen[target_url]: print line
Sự chuẩn bị
Trước khi bất kỳ yêu cầu nào có thể xảy ra, một [1] thư viện mới sẽ yêu cầu cài đặt.
- Thư viện yêu cầu cho phép truy cập vào nhiều phương thức của nó và làm cho thao tác dữ liệu trở nên dễ dàng!
Để cài đặt thư viện này, điều hướng đến một thiết bị đầu cuối IDE. Tại dấu nhắc lệnh [
import urllib2
for line in urllib2.urlopen[target_url]:
print line
7], thực thi mã bên dưới. Đối với thiết bị đầu cuối được sử dụng trong ví dụ này, dấu nhắc lệnh là dấu hiệu đô la [import urllib2
for line in urllib2.urlopen[target_url]:
print line
7]. Lời nhắc thiết bị đầu cuối của bạn có thể khác nhau.$ pip install requests
Nhấn phím trên bàn phím để bắt đầu quá trình cài đặt.
Nếu cài đặt thành công, một thông báo sẽ hiển thị trong thiết bị đầu cuối cho biết giống nhau.
Vui lòng xem hướng dẫn cài đặt Pycharm cho thư viện cần thiết.
- Cách cài đặt các yêu cầu trên Pycharm
Thêm mã sau vào đầu mỗi đoạn mã. Đoạn trích này sẽ cho phép mã trong bài viết này chạy không có lỗi.
import urllib.request import requests import urllib from urllib.request import urlopen import urllib3
Phương pháp 1: Sử dụng Urllib.Request []. Urlopen []
Phương thức này gọi trong thư viện
import urllib2
for line in urllib2.urlopen[target_url]:
print line
9 và sử dụng hàm import urllib2
data = urllib2.urlopen["//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
0 để mở một URL được chỉ định, đọc nội dung một dòng tại một thời điểm và áp dụng tùy chọn giải mã thích hợp [import urllib2
data = urllib2.urlopen["//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
1].file_url = '//raw.githubusercontent.com/finxter/FinxterTutorials/main/nlights.txt' for line in urllib.request.urlopen[file_url]: print[line.decode['utf-8']]
Mã này tuyên bố một URL nơi
import urllib2
data = urllib2.urlopen["//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
2 được đặt và lưu vị trí này vào import urllib2
data = urllib2.urlopen["//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
3.Tiếp theo, vòng lặp
import urllib2
data = urllib2.urlopen["//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
4 được khởi tạo để truy cập URL được chỉ định và đọc nội dung trong một dòng tại một thời điểm. Các dòng được đầu ra cho thiết bị đầu cuối sau khi áp dụng import urllib2
data = urllib2.urlopen["//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
1.& Nbsp; Lưu ý: Bấm vào đây để biết thêm thông tin về giải mã.Note: Click here for more additional information on decoding.
Đầu ra
Đầu ra từ phương thức này là một kiểu dữ liệu chuỗi với các dòng trống phân tách các đoạn.
import urllib2
data = urllib2.urlopen["//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
6import urllib2
data = urllib2.urlopen["//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
7import urllib2
data = urllib2.urlopen["//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
8Phương pháp 2: Sử dụng Yêu cầu []
Phương thức này gọi trong thư viện
import urllib2
data = urllib2.urlopen["//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
9 và sử dụng 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
0 để truy cập tệp văn bản được đặt tại URL được chỉ định, đọc nội dung theo một dòng tại một thời điểm và xuất dưới dạng tuple.file_url = '//raw.githubusercontent.com/finxter/FinxterTutorials/main/nlights.txt' response = requests.get[file_url] if [response.status_code]: data = response.text for line in enumerate[data.split['\n']]: print[line]
Mã này tuyên bố một URL nơi
import urllib2
data = urllib2.urlopen["//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
2 được đặt và lưu vị trí này vào import urllib2
data = urllib2.urlopen["//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
3.Tiếp theo, vòng lặp
import urllib2
data = urllib2.urlopen["//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
4 được khởi tạo để truy cập URL được chỉ định và đọc nội dung trong một dòng tại một thời điểm. Các dòng được đầu ra cho thiết bị đầu cuối sau khi áp dụng import urllib2
data = urllib2.urlopen["//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
1.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
5& Nbsp; Lưu ý: Bấm vào đây để biết thêm thông tin về giải mã.
- Đầu ra
- Đầu ra từ phương thức này là một kiểu dữ liệu chuỗi với các dòng trống phân tách các đoạn.
Đầu ra
Đầu ra từ phương thức này là một kiểu dữ liệu chuỗi với các dòng trống phân tách các đoạn.
$ pip install requests1
Phương pháp 2: Sử dụng Yêu cầu []Note: This code appends an empty blank line [
$ pip install requests2] to the output.
Phương thức này gọi trong thư viện import urllib2
data = urllib2.urlopen["//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
9 và sử dụng 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
0 để truy cập tệp văn bản được đặt tại URL được chỉ định, đọc nội dung theo một dòng tại một thời điểm và xuất dưới dạng tuple.
import urllib2
data = urllib2.urlopen["//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
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
Sau đó
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
3 được tuyên bố. Dòng này cố gắng kết nối với URL được hiển thị ở trên và trả về 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
4. Nếu thành công, lợi nhuận sau đây.import urllib2
for line in urllib2.urlopen[target_url]:
print line
3
object. From this object, the code attempts to get the contents [$ pip install requests6], and apply the appropriate decoding [
import urllib2
data = urllib2.urlopen["//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
1] option to the same.file_url = '//raw.githubusercontent.com/finxter/FinxterTutorials/main/nlights.txt' http = urllib3.PoolManager[] response = http.request['GET', file_url] data = response.data.decode['utf-8'] print[data]
Tiếp theo, mã kiểm tra để xem liệu
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
6 là 200 [kết nối thành công]. Nếu đúng, mã bên trong câu lệnh 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
7 sẽ thực thi như sau.Biến
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
8RetRieves và lưu tất cả các văn bản bên trong tệp import urllib2
data = urllib2.urlopen["//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
2.import urllib.request import requests import urllib from urllib.request import urlopen import urllib31
A For Loop được khởi tạo để đọc trong một dòng tại một thời điểm, tách dòng trên ký tự dòng mới [
$ pip install requests0] và xuất mỗi dòng bằng định dạng in.
Đầu ra cho phương pháp này là bốn [4] bộ dữ liệu, mỗi bộ chứa một số dòng và nội dung của đoạn tương ứng.
Đầu ra
Đầu ra từ phương thức này là một kiểu dữ liệu chuỗi với các dòng trống phân tách các đoạn.no blank lines separating the paragraphs.
import urllib.request import requests import urllib from urllib.request import urlopen import urllib37
Phương pháp 2: Sử dụng Yêu cầu []
Phương thức này gọi trong thư viện
import urllib2
data = urllib2.urlopen["//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
9 và sử dụng 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
0 để truy cập tệp văn bản được đặt tại URL được chỉ định, đọc nội dung theo một dòng tại một thời điểm và xuất dưới dạng tuple.one-liner to connect to the specified URL, read a specified number of file characters, and apply the appropriate decoding [
import urllib2
data = urllib2.urlopen["//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
1] option to the same.file_url = '//raw.githubusercontent.com/finxter/FinxterTutorials/main/nlights.txt' data = urlopen[file_url].read[203].decode['utf-8'] print[data]
Sau đó
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
3 được tuyên bố. Dòng này cố gắng kết nối với URL được hiển thị ở trên và trả về 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
4. Nếu thành công, lợi nhuận sau đây.Đầu ra
Đầu ra từ phương thức này là một kiểu dữ liệu chuỗi với các dòng trống phân tách các đoạn.
import urllib2
data = urllib2.urlopen["//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
6Phương pháp 2: Sử dụng Yêu cầu []
Phương thức này gọi trong thư viện
import urllib2
data = urllib2.urlopen["//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
9 và sử dụng 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
0 để truy cập tệp văn bản được đặt tại URL được chỉ định, đọc nội dung theo một dòng tại một thời điểm và xuất dưới dạng tuple.import urllib2
for line in urllib2.urlopen[target_url]:
print line
0Mã này tuyên bố một URL nơi
import urllib2
data = urllib2.urlopen["//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
2 được đặt và lưu vị trí này vào import urllib2
data = urllib2.urlopen["//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
3.Trên một dòng, URL được chỉ định được mở, đọc trong, được giải mã và lưu đến
import urllib.request import requests import urllib from urllib.request import urlopen import urllib34. Đầu ra sau đó được gửi đến thiết bị đầu cuối.
Đầu ra
Đầu ra từ phương thức này là một kiểu dữ liệu chuỗi không có dòng trống phân tách các đoạn văn.no blank lines separating the paragraphs.
file_url = '//raw.githubusercontent.com/finxter/FinxterTutorials/main/nlights.txt' for line in urllib.request.urlopen[file_url]: print[line.decode['utf-8']]9
Bản tóm tắt
Năm [5] phương thức về cách đọc tệp văn bản từ URL sẽ cung cấp cho bạn đủ thông tin để chọn phương pháp tốt nhất cho các yêu cầu mã hóa của bạn.
Chúc may mắn và mã hóa hạnh phúc!
Ở trường đại học, tôi tìm thấy tình yêu viết và mã hóa của mình. Cả hai trong số đó tôi đã có thể sử dụng trong sự nghiệp của mình.
Trong 15 năm qua, tôi đã giữ một số vị trí như:
Nhà văn kỹ thuật của công ty nội bộ cho các chương trình phần mềm khác nhau như Navision và Microsoft CRM Corporate Huấn luyện viên [nhân viên của 30+]
Corporate Trainer [staff of 30+]
Programming Instructor
Implementation Specialist for Navision and Microsoft CRM
Senior PHP Coder