Tác nhân người dùng python
Cho em hỏi muốn thay đổi tác nhân người dùng của chrome, firefox phải làm như thế nào ạ Show muốn nhập vào trình duyệt để cho nó chạy với mã đó. Có bản dịch tiếng Pháp của bản sửa đổi trước đó của HOWTO này, có sẵn tại urllib2 - Le Manuel manquant Giới thiệuNhững bài viết liên quan Bạn cũng có thể thấy hữu ích với bài viết sau về tìm nạp tài nguyên web bằng Python
urllib. yêu cầu là một mô-đun Python để tìm nạp URL (Bộ định vị tài nguyên thống nhất). Nó cung cấp một giao diện rất đơn giản, dưới dạng chức năng urlopen. Điều này có khả năng tìm nạp URL bằng nhiều giao thức khác nhau. Nó cũng cung cấp một giao diện phức tạp hơn một chút để xử lý các tình huống phổ biến - như xác thực cơ bản, cookie, proxy, v.v. Chúng được cung cấp bởi các đối tượng được gọi là trình xử lý và trình mở urllib. yêu cầu hỗ trợ tìm nạp URL cho nhiều “lược đồ URL” (được xác định bằng chuỗi trước import shutil import tempfile import urllib.request with urllib.request.urlopen('http://python.org/') as response: with tempfile.NamedTemporaryFile(delete=False) as tmp_file: shutil.copyfileobj(response, tmp_file) with open(tmp_file.name) as html: pass6 trong URL - ví dụ: import shutil import tempfile import urllib.request with urllib.request.urlopen('http://python.org/') as response: with tempfile.NamedTemporaryFile(delete=False) as tmp_file: shutil.copyfileobj(response, tmp_file) with open(tmp_file.name) as html: pass7 là lược đồ URL của import shutil import tempfile import urllib.request with urllib.request.urlopen('http://python.org/') as response: with tempfile.NamedTemporaryFile(delete=False) as tmp_file: shutil.copyfileobj(response, tmp_file) with open(tmp_file.name) as html: pass8) bằng cách sử dụng các giao thức mạng được liên kết của chúng (e. g. FTP, HTTP). Hướng dẫn này tập trung vào trường hợp phổ biến nhất, HTTP Đối với các tình huống đơn giản, urlopen rất dễ sử dụng. Nhưng ngay khi bạn gặp lỗi hoặc các trường hợp không nhỏ khi mở URL HTTP, bạn sẽ cần một số hiểu biết về Giao thức truyền tải siêu văn bản. Tài liệu tham khảo toàn diện và có thẩm quyền nhất về HTTP là RFC 2616. Đây là một tài liệu kỹ thuật và không nhằm mục đích dễ đọc. HOWTO này nhằm mục đích minh họa việc sử dụng urllib, với đủ chi tiết về HTTP để giúp bạn vượt qua. Nó không nhằm mục đích thay thế các tài liệu, nhưng bổ sung cho chúng Tìm nạp URLCách đơn giản nhất để sử dụng urllib. yêu cầu như sau import urllib.request with urllib.request.urlopen('http://python.org/') as response: html = response.read() Nếu bạn muốn truy xuất một tài nguyên qua URL và lưu trữ nó ở một vị trí tạm thời, bạn có thể làm như vậy thông qua các chức năng và import shutil import tempfile import urllib.request with urllib.request.urlopen('http://python.org/') as response: with tempfile.NamedTemporaryFile(delete=False) as tmp_file: shutil.copyfileobj(response, tmp_file) with open(tmp_file.name) as html: pass Nhiều cách sử dụng urllib sẽ đơn giản như vậy (lưu ý rằng thay vì 'http. ’ URL mà chúng tôi có thể đã sử dụng một URL bắt đầu bằng ‘ftp. ', 'tài liệu. ', vân vân. ). Tuy nhiên, mục đích của hướng dẫn này là giải thích các trường hợp phức tạp hơn, tập trung vào HTTP HTTP dựa trên các yêu cầu và phản hồi - máy khách đưa ra yêu cầu và máy chủ gửi phản hồi. urllib. yêu cầu phản ánh điều này với một đối tượng import urllib.request req = urllib.request.Request('http://www.voidspace.org.uk') with urllib.request.urlopen(req) as response: the_page = response.read()2 đại diện cho yêu cầu HTTP mà bạn đang thực hiện. Ở dạng đơn giản nhất, bạn tạo một đối tượng Yêu cầu chỉ định URL bạn muốn tìm nạp. Gọi import urllib.request req = urllib.request.Request('http://www.voidspace.org.uk') with urllib.request.urlopen(req) as response: the_page = response.read()3 với đối tượng Yêu cầu này trả về một đối tượng phản hồi cho URL được yêu cầu. Phản hồi này là một đối tượng giống như tệp, có nghĩa là bạn có thể gọi import urllib.request req = urllib.request.Request('http://www.voidspace.org.uk') with urllib.request.urlopen(req) as response: the_page = response.read()4 chẳng hạn trên phản hồi import urllib.request req = urllib.request.Request('http://www.voidspace.org.uk') with urllib.request.urlopen(req) as response: the_page = response.read() Lưu ý rằng urllib. yêu cầu sử dụng cùng một giao diện Yêu cầu để xử lý tất cả các lược đồ URL. Ví dụ: bạn có thể thực hiện một yêu cầu FTP như vậy req = urllib.request.Request('ftp://example.com/') Trong trường hợp của HTTP, có hai điều bổ sung mà các đối tượng Yêu cầu cho phép bạn thực hiện. Đầu tiên, bạn có thể truyền dữ liệu để gửi đến máy chủ. Thứ hai, bạn có thể chuyển thông tin bổ sung (“siêu dữ liệu”) về dữ liệu hoặc về chính yêu cầu tới máy chủ - thông tin này được gửi dưới dạng “tiêu đề” HTTP. Hãy lần lượt xem xét từng vấn đề này Dữ liệuĐôi khi bạn muốn gửi dữ liệu tới một URL (thường URL sẽ đề cập đến tập lệnh CGI (Giao diện cổng chung) hoặc ứng dụng web khác). Với HTTP, điều này thường được thực hiện bằng cách sử dụng cái được gọi là yêu cầu POST. Đây thường là những gì trình duyệt của bạn thực hiện khi bạn gửi biểu mẫu HTML mà bạn đã điền trên web. Không phải tất cả các POST đều phải đến từ các biểu mẫu. bạn có thể sử dụng POST để truyền dữ liệu tùy ý đến ứng dụng của riêng mình. Trong trường hợp phổ biến của các biểu mẫu HTML, dữ liệu cần được mã hóa theo cách tiêu chuẩn, sau đó được chuyển đến đối tượng Yêu cầu dưới dạng đối số import urllib.request req = urllib.request.Request('http://www.voidspace.org.uk') with urllib.request.urlopen(req) as response: the_page = response.read()5. Việc mã hóa được thực hiện bằng một chức năng từ thư viện import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' values = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } data = urllib.parse.urlencode(values) data = data.encode('ascii') # data should be bytes req = urllib.request.Request(url, data) with urllib.request.urlopen(req) as response: the_page = response.read() Lưu ý rằng các mã hóa khác đôi khi được yêu cầu (e. g. để tải tệp lên từ biểu mẫu HTML - xem để biết thêm chi tiết) Nếu bạn không vượt qua đối số import urllib.request req = urllib.request.Request('http://www.voidspace.org.uk') with urllib.request.urlopen(req) as response: the_page = response.read()5, urllib sẽ sử dụng yêu cầu GET. Một cách mà các yêu cầu GET và POST khác nhau là các yêu cầu POST thường có “tác dụng phụ”. họ thay đổi trạng thái của hệ thống theo một cách nào đó (ví dụ: bằng cách đặt hàng trên trang web để chuyển đến tận nhà bạn một trăm cân thư rác đóng hộp). Mặc dù tiêu chuẩn HTTP làm rõ rằng các POST nhằm mục đích luôn gây ra tác dụng phụ và yêu cầu GET không bao giờ gây ra tác dụng phụ, nhưng không có gì ngăn cản yêu cầu GET có tác dụng phụ, cũng như yêu cầu POST không có tác dụng phụ. Dữ liệu cũng có thể được truyền trong một yêu cầu HTTP GET bằng cách mã hóa nó trong chính URL Điều này được thực hiện như sau >>> import urllib.request >>> import urllib.parse >>> data = {} >>> data['name'] = 'Somebody Here' >>> data['location'] = 'Northampton' >>> data['language'] = 'Python' >>> url_values = urllib.parse.urlencode(data) >>> print(url_values) # The order may differ from below. name=Somebody+Here&language=Python&location=Northampton >>> url = 'http://www.example.com/example.cgi' >>> full_url = url + '?' + url_values >>> data = urllib.request.urlopen(full_url) Lưu ý rằng URL đầy đủ được tạo bằng cách thêm import urllib.request req = urllib.request.Request('http://www.voidspace.org.uk') with urllib.request.urlopen(req) as response: the_page = response.read()8 vào URL, theo sau là các giá trị được mã hóa tiêu đềChúng ta sẽ thảo luận ở đây một tiêu đề HTTP cụ thể, để minh họa cách thêm tiêu đề vào yêu cầu HTTP của bạn Một số trang web không thích bị duyệt bởi các chương trình hoặc gửi các phiên bản khác nhau cho các trình duyệt khác nhau. Theo mặc định, urllib tự nhận dạng là import urllib.request req = urllib.request.Request('http://www.voidspace.org.uk') with urllib.request.urlopen(req) as response: the_page = response.read()9 (trong đó req = urllib.request.Request('ftp://example.com/')0 và req = urllib.request.Request('ftp://example.com/')1 là số phiên bản chính và phụ của bản phát hành Python, e. g. req = urllib.request.Request('ftp://example.com/')2), điều này có thể gây nhầm lẫn cho trang web hoặc đơn giản là không hoạt động. Cách trình duyệt tự xác định chính nó là thông qua tiêu đề req = urllib.request.Request('ftp://example.com/')3. Khi bạn tạo một đối tượng Yêu cầu, bạn có thể chuyển từ điển các tiêu đề vào. Ví dụ sau đưa ra yêu cầu tương tự như trên, nhưng tự nhận dạng chính nó là một phiên bản của Internet Explorer import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' } headers = {'User-Agent': user_agent} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: the_page = response.read() Phản hồi cũng có hai phương pháp hữu ích. Xem phần tiếp theo sau khi chúng ta xem xét điều gì sẽ xảy ra khi có sự cố xảy ra Xử lý ngoại lệurlopen tăng req = urllib.request.Request('ftp://example.com/')4 khi nó không thể xử lý phản hồi (mặc dù như thường lệ với API Python, các ngoại lệ tích hợp sẵn như , v.v. cũng có thể được nâng lên) req = urllib.request.Request('ftp://example.com/')7 là lớp con của req = urllib.request.Request('ftp://example.com/')4 được nêu ra trong trường hợp cụ thể của URL HTTP Các lớp ngoại lệ được xuất từ mô-đun URLLỗiThông thường, URLError xuất hiện do không có kết nối mạng (không có tuyến đến máy chủ được chỉ định) hoặc máy chủ được chỉ định không tồn tại. Trong trường hợp này, ngoại lệ được đưa ra sẽ có thuộc tính 'lý do', là một bộ chứa mã lỗi và thông báo lỗi văn bản e. g >>> req = urllib.request.Request('http://www.pretend_server.org') >>> try: urllib.request.urlopen(req) .. except urllib.error.URLError as e: .. print(e.reason) ... (4, 'getaddrinfo failed') Lỗi HTTPMỗi phản hồi HTTP từ máy chủ chứa một “mã trạng thái” dạng số. Đôi khi mã trạng thái cho biết máy chủ không thể thực hiện yêu cầu. Trình xử lý mặc định sẽ xử lý một số phản hồi này cho bạn (ví dụ: nếu phản hồi là "chuyển hướng" yêu cầu ứng dụng khách tìm nạp tài liệu từ một URL khác, thì urllib sẽ xử lý việc đó cho bạn). Đối với những thứ mà nó không thể xử lý, urlopen sẽ tăng req = urllib.request.Request('ftp://example.com/')7. Các lỗi điển hình bao gồm '404' (không tìm thấy trang), '403' (yêu cầu bị cấm) và '401' (yêu cầu xác thực) Xem phần 10 của RFC 2616 để tham khảo về tất cả các mã lỗi HTTP Phiên bản req = urllib.request.Request('ftp://example.com/')7 được đưa ra sẽ có thuộc tính 'mã' số nguyên, tương ứng với lỗi do máy chủ gửi Mã lỗiBởi vì trình xử lý mặc định xử lý chuyển hướng (mã trong phạm vi 300) và mã trong phạm vi 100–299 biểu thị thành công, bạn sẽ thường chỉ thấy mã lỗi trong phạm vi 400–599 là một từ điển mã phản hồi hữu ích trong đó hiển thị tất cả các mã phản hồi được sử dụng bởi RFC 2616. Từ điển được sao chép ở đây để thuận tiện # Table mapping response codes to messages; entries have the # form {code: (shortmessage, longmessage)}. responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), } Khi xảy ra lỗi, máy chủ sẽ phản hồi bằng cách trả về mã lỗi HTTP và trang lỗi. Bạn có thể sử dụng phiên bản req = urllib.request.Request('ftp://example.com/')7 làm phản hồi trên trang được trả về. Điều này có nghĩa là cũng như thuộc tính code, nó cũng có các phương thức read, geturl và info, như được trả về bởi mô-đun import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' values = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } data = urllib.parse.urlencode(values) data = data.encode('ascii') # data should be bytes req = urllib.request.Request(url, data) with urllib.request.urlopen(req) as response: the_page = response.read()4 >>> req = urllib.request.Request('http://www.python.org/fish.html') >>> try: .. urllib.request.urlopen(req) .. except urllib.error.HTTPError as e: .. print(e.code) .. print(e.read()) ... 404 b' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n ... Kết thúc nóVì vậy, nếu bạn muốn chuẩn bị cho req = urllib.request.Request('ftp://example.com/')7 hoặc req = urllib.request.Request('ftp://example.com/')4, có hai cách tiếp cận cơ bản. Tôi thích cách tiếp cận thứ hai Số 1import shutil import tempfile import urllib.request with urllib.request.urlopen('http://python.org/') as response: with tempfile.NamedTemporaryFile(delete=False) as tmp_file: shutil.copyfileobj(response, tmp_file) with open(tmp_file.name) as html: pass0 Ghi chú import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' values = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } data = urllib.parse.urlencode(values) data = data.encode('ascii') # data should be bytes req = urllib.request.Request(url, data) with urllib.request.urlopen(req) as response: the_page = response.read()7 phải đến trước, nếu không thì import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' values = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } data = urllib.parse.urlencode(values) data = data.encode('ascii') # data should be bytes req = urllib.request.Request(url, data) with urllib.request.urlopen(req) as response: the_page = response.read()8 cũng sẽ bắt được req = urllib.request.Request('ftp://example.com/')7 Số 2import shutil import tempfile import urllib.request with urllib.request.urlopen('http://python.org/') as response: with tempfile.NamedTemporaryFile(delete=False) as tmp_file: shutil.copyfileobj(response, tmp_file) with open(tmp_file.name) as html: pass1 thông tin và geturlPhản hồi được trả về bởi urlopen (hoặc đối tượng req = urllib.request.Request('ftp://example.com/')7) có hai phương thức hữu ích là >>> import urllib.request >>> import urllib.parse >>> data = {} >>> data['name'] = 'Somebody Here' >>> data['location'] = 'Northampton' >>> data['language'] = 'Python' >>> url_values = urllib.parse.urlencode(data) >>> print(url_values) # The order may differ from below. name=Somebody+Here&language=Python&location=Northampton >>> url = 'http://www.example.com/example.cgi' >>> full_url = url + '?' + url_values >>> data = urllib.request.urlopen(full_url)1 và >>> import urllib.request >>> import urllib.parse >>> data = {} >>> data['name'] = 'Somebody Here' >>> data['location'] = 'Northampton' >>> data['language'] = 'Python' >>> url_values = urllib.parse.urlencode(data) >>> print(url_values) # The order may differ from below. name=Somebody+Here&language=Python&location=Northampton >>> url = 'http://www.example.com/example.cgi' >>> full_url = url + '?' + url_values >>> data = urllib.request.urlopen(full_url)2 và được xác định trong mô-đun geturl - cái này trả về URL thực của trang được tìm nạp. Điều này hữu ích vì import urllib.request req = urllib.request.Request('http://www.voidspace.org.uk') with urllib.request.urlopen(req) as response: the_page = response.read()3 (hoặc đối tượng mở được sử dụng) có thể đã theo một chuyển hướng. URL của trang được tìm nạp có thể không giống với URL được yêu cầu thông tin - điều này trả về một đối tượng giống như từ điển mô tả trang đã tìm nạp, đặc biệt là các tiêu đề do máy chủ gửi. Nó hiện là một phiên bản >>> import urllib.request >>> import urllib.parse >>> data = {} >>> data['name'] = 'Somebody Here' >>> data['location'] = 'Northampton' >>> data['language'] = 'Python' >>> url_values = urllib.parse.urlencode(data) >>> print(url_values) # The order may differ from below. name=Somebody+Here&language=Python&location=Northampton >>> url = 'http://www.example.com/example.cgi' >>> full_url = url + '?' + url_values >>> data = urllib.request.urlopen(full_url)5 Các tiêu đề điển hình bao gồm 'Độ dài nội dung', 'Loại nội dung', v.v. Xem Tham khảo nhanh về Tiêu đề HTTP để biết danh sách tiêu đề HTTP hữu ích với giải thích ngắn gọn về ý nghĩa và cách sử dụng của chúng Dụng cụ mở và xử lýKhi bạn tìm nạp một URL, bạn sử dụng một công cụ mở (một ví dụ về cái tên có lẽ gây nhầm lẫn). Thông thường, chúng tôi đã sử dụng công cụ mở mặc định - thông qua import urllib.request req = urllib.request.Request('http://www.voidspace.org.uk') with urllib.request.urlopen(req) as response: the_page = response.read()3 - nhưng bạn có thể tạo công cụ mở tùy chỉnh. Người mở sử dụng bộ xử lý. Tất cả những việc “nâng vật nặng” được thực hiện bởi những người xử lý. Mỗi trình xử lý biết cách mở URL cho một sơ đồ URL cụ thể (http, ftp, v.v. ) hoặc cách xử lý khía cạnh mở URL, chẳng hạn như chuyển hướng HTTP hoặc cookie HTTP Bạn sẽ muốn tạo các công cụ mở nếu bạn muốn tìm nạp các URL đã cài đặt các trình xử lý cụ thể, chẳng hạn để tải một công cụ mở xử lý cookie hoặc để tải một công cụ mở không xử lý các chuyển hướng Để tạo công cụ mở, hãy khởi tạo một >>> import urllib.request >>> import urllib.parse >>> data = {} >>> data['name'] = 'Somebody Here' >>> data['location'] = 'Northampton' >>> data['language'] = 'Python' >>> url_values = urllib.parse.urlencode(data) >>> print(url_values) # The order may differ from below. name=Somebody+Here&language=Python&location=Northampton >>> url = 'http://www.example.com/example.cgi' >>> full_url = url + '?' + url_values >>> data = urllib.request.urlopen(full_url)8, sau đó gọi liên tục >>> import urllib.request >>> import urllib.parse >>> data = {} >>> data['name'] = 'Somebody Here' >>> data['location'] = 'Northampton' >>> data['language'] = 'Python' >>> url_values = urllib.parse.urlencode(data) >>> print(url_values) # The order may differ from below. name=Somebody+Here&language=Python&location=Northampton >>> url = 'http://www.example.com/example.cgi' >>> full_url = url + '?' + url_values >>> data = urllib.request.urlopen(full_url)9 Ngoài ra, bạn có thể sử dụng import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' } headers = {'User-Agent': user_agent} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: the_page = response.read()0, đây là một hàm tiện lợi để tạo các đối tượng mở bằng một lệnh gọi hàm duy nhất. import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' } headers = {'User-Agent': user_agent} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: the_page = response.read()0 thêm một số trình xử lý theo mặc định, nhưng cung cấp một cách nhanh chóng để thêm nhiều hơn và/hoặc ghi đè lên các trình xử lý mặc định Các loại trình xử lý khác mà bạn có thể muốn có thể xử lý proxy, xác thực và các tình huống phổ biến nhưng hơi chuyên biệt khác import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' } headers = {'User-Agent': user_agent} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: the_page = response.read()2 có thể được sử dụng để biến một đối tượng import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' } headers = {'User-Agent': user_agent} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: the_page = response.read()3 thành công cụ mở mặc định (toàn cầu). Điều này có nghĩa là các cuộc gọi đến import urllib.request req = urllib.request.Request('http://www.voidspace.org.uk') with urllib.request.urlopen(req) as response: the_page = response.read()3 sẽ sử dụng công cụ mở mà bạn đã cài đặt Các đối tượng opener có một phương thức import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' } headers = {'User-Agent': user_agent} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: the_page = response.read()5, có thể được gọi trực tiếp để tìm nạp các url giống như cách của hàm import urllib.request req = urllib.request.Request('http://www.voidspace.org.uk') with urllib.request.urlopen(req) as response: the_page = response.read()3. không cần gọi import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' } headers = {'User-Agent': user_agent} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: the_page = response.read()2, ngoại trừ để thuận tiện Xác thực cơ bảnĐể minh họa việc tạo và cài đặt trình xử lý, chúng tôi sẽ sử dụng import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' } headers = {'User-Agent': user_agent} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: the_page = response.read()8. Để thảo luận chi tiết hơn về chủ đề này – bao gồm giải thích về cách thức hoạt động của Xác thực Cơ bản – hãy xem Hướng dẫn Xác thực Cơ bản Khi yêu cầu xác thực, máy chủ sẽ gửi tiêu đề (cũng như mã lỗi 401) yêu cầu xác thực. Điều này chỉ định sơ đồ xác thực và 'lĩnh vực'. Tiêu đề trông giống như. import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' } headers = {'User-Agent': user_agent} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: the_page = response.read()9 e. g import shutil import tempfile import urllib.request with urllib.request.urlopen('http://python.org/') as response: with tempfile.NamedTemporaryFile(delete=False) as tmp_file: shutil.copyfileobj(response, tmp_file) with open(tmp_file.name) as html: pass2 Sau đó, khách hàng nên thử lại yêu cầu với tên và mật khẩu phù hợp cho lĩnh vực được bao gồm dưới dạng tiêu đề trong yêu cầu. Đây là 'xác thực cơ bản'. Để đơn giản hóa quy trình này, chúng tôi có thể tạo một phiên bản của import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' } headers = {'User-Agent': user_agent} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: the_page = response.read()8 và một công cụ mở để sử dụng trình xử lý này import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' } headers = {'User-Agent': user_agent} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: the_page = response.read()8 sử dụng một đối tượng được gọi là trình quản lý mật khẩu để xử lý ánh xạ URL và vùng với mật khẩu và tên người dùng. Nếu bạn biết lĩnh vực là gì (từ tiêu đề xác thực được gửi bởi máy chủ), thì bạn có thể sử dụng >>> req = urllib.request.Request('http://www.pretend_server.org') >>> try: urllib.request.urlopen(req) .. except urllib.error.URLError as e: .. print(e.reason) ... (4, 'getaddrinfo failed')2. Thường người ta không quan tâm cảnh giới là gì. Trong trường hợp đó, thật thuận tiện khi sử dụng >>> req = urllib.request.Request('http://www.pretend_server.org') >>> try: urllib.request.urlopen(req) .. except urllib.error.URLError as e: .. print(e.reason) ... (4, 'getaddrinfo failed')3. Điều này cho phép bạn chỉ định tên người dùng và mật khẩu mặc định cho một URL. Điều này sẽ được cung cấp trong trường hợp bạn không cung cấp kết hợp thay thế cho một lĩnh vực cụ thể. Chúng tôi chỉ ra điều này bằng cách cung cấp >>> req = urllib.request.Request('http://www.pretend_server.org') >>> try: urllib.request.urlopen(req) .. except urllib.error.URLError as e: .. print(e.reason) ... (4, 'getaddrinfo failed')4 làm đối số lĩnh vực cho phương pháp >>> req = urllib.request.Request('http://www.pretend_server.org') >>> try: urllib.request.urlopen(req) .. except urllib.error.URLError as e: .. print(e.reason) ... (4, 'getaddrinfo failed')5 URL cấp cao nhất là URL đầu tiên yêu cầu xác thực. URL “sâu hơn” so với URL bạn chuyển đến. add_password() cũng sẽ khớp import shutil import tempfile import urllib.request with urllib.request.urlopen('http://python.org/') as response: with tempfile.NamedTemporaryFile(delete=False) as tmp_file: shutil.copyfileobj(response, tmp_file) with open(tmp_file.name) as html: pass3 Ghi chú Trong ví dụ trên, chúng tôi chỉ cung cấp import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' } headers = {'User-Agent': user_agent} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: the_page = response.read()8 cho import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' } headers = {'User-Agent': user_agent} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data, headers) with urllib.request.urlopen(req) as response: the_page = response.read()0. Theo mặc định, trình mở có trình xử lý cho các tình huống thông thường – >>> req = urllib.request.Request('http://www.pretend_server.org') >>> try: urllib.request.urlopen(req) .. except urllib.error.URLError as e: .. print(e.reason) ... (4, 'getaddrinfo failed')8 (nếu cài đặt proxy như biến môi trường >>> req = urllib.request.Request('http://www.pretend_server.org') >>> try: urllib.request.urlopen(req) .. except urllib.error.URLError as e: .. print(e.reason) ... (4, 'getaddrinfo failed')9 được đặt), # Table mapping response codes to messages; entries have the # form {code: (shortmessage, longmessage)}. responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), }0, # Table mapping response codes to messages; entries have the # form {code: (shortmessage, longmessage)}. responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), }1, # Table mapping response codes to messages; entries have the # form {code: (shortmessage, longmessage)}. responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), }2, # Table mapping response codes to messages; entries have the # form {code: (shortmessage, longmessage)}. responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), }3, # Table mapping response codes to messages; entries have the # form {code: (shortmessage, longmessage)}. responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), }4, # Table mapping response codes to messages; entries have the # form {code: (shortmessage, longmessage)}. responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), }5, # Table mapping response codes to messages; entries have the # form {code: (shortmessage, longmessage)}. responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), }6, # Table mapping response codes to messages; entries have the # form {code: (shortmessage, longmessage)}. responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), }7 # Table mapping response codes to messages; entries have the # form {code: (shortmessage, longmessage)}. responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), }8 trên thực tế hoặc là một URL đầy đủ (bao gồm cả 'http. ’ thành phần lược đồ và tên máy chủ và tùy chọn số cổng) e. g. # Table mapping response codes to messages; entries have the # form {code: (shortmessage, longmessage)}. responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), }9 hoặc một “cơ quan có thẩm quyền” (i. e. tên máy chủ, tùy chọn bao gồm số cổng) e. g. >>> req = urllib.request.Request('http://www.python.org/fish.html') >>> try: .. urllib.request.urlopen(req) .. except urllib.error.HTTPError as e: .. print(e.code) .. print(e.read()) ... 404 b' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n ...0 hoặc >>> req = urllib.request.Request('http://www.python.org/fish.html') >>> try: .. urllib.request.urlopen(req) .. except urllib.error.HTTPError as e: .. print(e.code) .. print(e.read()) ... 404 b' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n ...1 (ví dụ sau bao gồm số cổng). Cơ quan, nếu có, KHÔNG được chứa thành phần “thông tin người dùng” - ví dụ: >>> req = urllib.request.Request('http://www.python.org/fish.html') >>> try: .. urllib.request.urlopen(req) .. except urllib.error.HTTPError as e: .. print(e.code) .. print(e.read()) ... 404 b' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n ...2 là không chính xác proxyurllib sẽ tự động phát hiện cài đặt proxy của bạn và sử dụng chúng. Đây là thông qua >>> req = urllib.request.Request('http://www.pretend_server.org') >>> try: urllib.request.urlopen(req) .. except urllib.error.URLError as e: .. print(e.reason) ... (4, 'getaddrinfo failed')8, là một phần của chuỗi trình xử lý thông thường khi phát hiện cài đặt proxy. Thông thường đó là một điều tốt, nhưng có những trường hợp nó có thể không hữu ích. Một cách để làm điều này là thiết lập >>> req = urllib.request.Request('http://www.pretend_server.org') >>> try: urllib.request.urlopen(req) .. except urllib.error.URLError as e: .. print(e.reason) ... (4, 'getaddrinfo failed')8 của riêng chúng tôi, không có proxy nào được xác định. Điều này được thực hiện bằng các bước tương tự để thiết lập trình xử lý Xác thực Cơ bản import shutil import tempfile import urllib.request with urllib.request.urlopen('http://python.org/') as response: with tempfile.NamedTemporaryFile(delete=False) as tmp_file: shutil.copyfileobj(response, tmp_file) with open(tmp_file.name) as html: pass4 Ghi chú Hiện tại import shutil import tempfile import urllib.request with urllib.request.urlopen('http://python.org/') as response: with tempfile.NamedTemporaryFile(delete=False) as tmp_file: shutil.copyfileobj(response, tmp_file) with open(tmp_file.name) as html: pass9 không hỗ trợ tìm nạp >>> req = urllib.request.Request('http://www.python.org/fish.html') >>> try: .. urllib.request.urlopen(req) .. except urllib.error.HTTPError as e: .. print(e.code) .. print(e.read()) ... 404 b' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n ...6 vị trí thông qua proxy. Tuy nhiên, điều này có thể được kích hoạt bằng cách mở rộng urllib. yêu cầu như trong công thức Ghi chú >>> req = urllib.request.Request('http://www.python.org/fish.html') >>> try: .. urllib.request.urlopen(req) .. except urllib.error.HTTPError as e: .. print(e.code) .. print(e.read()) ... 404 b' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n ...7 sẽ bị bỏ qua nếu một biến >>> req = urllib.request.Request('http://www.python.org/fish.html') >>> try: .. urllib.request.urlopen(req) .. except urllib.error.HTTPError as e: .. print(e.code) .. print(e.read()) ... 404 b' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n ...8 được đặt; Ổ cắm và lớpHỗ trợ Python để tìm nạp tài nguyên từ web được phân lớp. urllib sử dụng thư viện, do đó sử dụng thư viện ổ cắm Kể từ Python 2. 3, bạn có thể chỉ định khoảng thời gian ổ cắm sẽ đợi phản hồi trước khi hết thời gian chờ. Điều này có thể hữu ích trong các ứng dụng phải tìm nạp các trang web. Theo mặc định, mô-đun ổ cắm không có thời gian chờ và có thể bị treo. Hiện tại, thời gian chờ của ổ cắm không được hiển thị tại http. khách hàng hoặc urllib. mức độ yêu cầu. Tuy nhiên, bạn có thể đặt thời gian chờ mặc định trên toàn cầu cho tất cả các ổ cắm bằng cách sử dụng import shutil import tempfile import urllib.request with urllib.request.urlopen('http://python.org/') as response: with tempfile.NamedTemporaryFile(delete=False) as tmp_file: shutil.copyfileobj(response, tmp_file) with open(tmp_file.name) as html: pass5 chú thíchTài liệu này đã được xem xét và sửa đổi bởi John Lee Google chẳng hạn Đánh hơi trình duyệt là một thực tế rất tồi đối với thiết kế trang web - xây dựng các trang web sử dụng các tiêu chuẩn web sẽ hợp lý hơn nhiều. Thật không may, nhiều trang web vẫn gửi các phiên bản khác nhau cho các trình duyệt khác nhau Tác nhân người dùng cho MSIE 6 là 'Mozilla/4. 0 (tương thích; MSIE 6. 0; . 1; . LƯỚI CLR 1. 1. 4322)' Để biết chi tiết về các tiêu đề yêu cầu HTTP khác, hãy xem Tham khảo nhanh về Tiêu đề HTTP Trong trường hợp của tôi, tôi phải sử dụng proxy để truy cập internet tại nơi làm việc. Nếu bạn cố tìm nạp các URL localhost thông qua proxy này, nó sẽ chặn chúng. IE được đặt để sử dụng proxy, mà urllib chọn trên. Để kiểm tra tập lệnh với máy chủ localhost, tôi phải ngăn urllib sử dụng proxy |