在Python中,使用urllib2
库发送HTTP请求并自定义标头,可以通过以下步骤实现:
import urllib2
url = "https://example.com"
headers = {
"User-Agent": "Mozilla/5.0",
"Custom-Header": "CustomHeaderValue"
}
request = urllib2.Request(url, headers=headers)
在这个例子中,我们设置了一个自定义标头Custom-Header
,其值为CustomHeaderValue
。
urllib2.urlopen()
方法发送请求:response = urllib2.urlopen(request)
response_content = response.read()
print(response_content)
完整代码如下:
import urllib2
url = "https://example.com"
headers = {
"User-Agent": "Mozilla/5.0",
"Custom-Header": "CustomHeaderValue"
}
request = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(request)
response_content = response.read()
print(response_content)
这样,您就可以在HTTP请求中使用urllib2
发送自定义标头了。
领取专属 10元无门槛券
手把手带您无忧上云