2011-10-28 10 views

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) 
+0

Chúng ta có thể làm điều tương tự với yêu cầu q.add_header ('apikey', 'xxx') – user3378649

+0

Ý anh là gì, @ user3378649? –

+1

@ 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

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()