كيف يمكنني إرسال رأس مخصص مع URLLIB2 في طلب HTTP؟

StackOverflow https://stackoverflow.com/questions/385262

  •  23-08-2019
  •  | 
  •  

سؤال

أريد إرسال رأس "قبول" مخصص في طلبي عند استخدام Urllib2.urlopen (..). كيف يمكنني فعل ذلك؟

هل كانت مفيدة؟

المحلول

ليس تماما. خلق شيء Request الكائن لا يرسل في الواقع الطلب، وطلب الكائنات ليس لديهم Read() طريقة. (أيضا: read() هو صغير.) كل ما عليك القيام به هو تمر Request كما الحجة الأولى ل urlopen() وهذا سوف يمنحك ردكم.

import urllib2
request = urllib2.Request("http://www.google.com", headers={"Accept" : "text/html"})
contents = urllib2.urlopen(request).read()

نصائح أخرى

أنا عادة استخدام:

import urllib2

request_headers = {
"Accept-Language": "en-US,en;q=0.5",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Referer": "http://thewebsite.com",
"Connection": "keep-alive" 
}

request = urllib2.Request("https://thewebsite.com", headers=request_headers)
response = urllib2.urlopen(request).read()
print(response)

بجانب الحلول الأخرى المذكورة بالفعل، يمكنك استخدام add_header طريقة.

لذلك، قدم المثال PYSTSGolem سيكون:

import urllib2
request = urllib2.Request("http://www.google.com")

request.add_header('Accept','text/html')

##Show the header having the key 'Accept'
request.get_header('Accept')

response = urllib2.urlopen(request)
response.read()
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top