Tôi khá mới với urllib của python. Những gì tôi cần làm là đặt tiêu đề tùy chỉnh cho yêu cầu được gửi tới máy chủ. Cụ thể, tôi cần đặt tiêu đề Loại nội dung và Ủy quyền. Tôi đã xem xét tài liệu python, nhưng tôi đã không thể tìm thấy nó.Làm cách nào để đặt tiêu đề bằng cách sử dụng urllib của python?
42
A
Trả lời
63
thêm tiêu đề HTTP sử dụng urllib2:
từ các tài liệu:
import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
resp = urllib2.urlopen(req)
content = resp.read()
9
Sử dụng urllib2 và tạo đối tượng Yêu cầu mà bạn sẽ chuyển đến urlopen. http://docs.python.org/library/urllib2.html
Tôi không thực sự sử dụng urllib "cũ" nữa.
req = urllib2.Request("http://google.com", None, {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'})
response = urllib2.urlopen(req).read()
chưa được kiểm tra ....
41
Đối với cả hai Python 3 và Python 2, công trình này:
try:
from urllib.request import Request, urlopen # Python 3
except ImportError:
from urllib2 import Request, urlopen # Python 2
q = Request('http://api.company.com/items/details?country=US&language=en')
q.add_header('apikey', 'xxx')
a = urlopen(q).read()
print(a)
1
Đối với nhiều tiêu đề làm như sau:
import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('param1', '212212')
req.add_header('param2', '12345678')
req.add_header('other_param1', 'sample')
req.add_header('other_param2', 'sample1111')
req.add_header('and_any_other_parame', 'testttt')
resp = urllib2.urlopen(req)
content = resp.read()
Chúng ta có thể làm điều tương tự với yêu cầu q.add_header ('apikey', 'xxx') – user3378649
Ý anh là gì, @ user3378649? –
@ user3378649 có thể là bạn có nghĩa là sử dụng gói python 'yêu cầu '[tiêu đề tùy chỉnh] (http://docs.python-requests.org/en/master/user/quickstart/#custom-headers) – WeizhongTu