urllib.request.Request python2 如何实现

发布时间: 更新时间: 总字数:149 阅读时间:1m 作者: IP上海 分享 网址

In Python 2, the equivalent of urllib.request.Request is urllib2.Request.

Here’s an example:

import urllib2

url = "https://example.com"
headers = {"User-Agent": "My User Agent"}
data = "foo=bar&baz=qux"

req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)

print(response.read())

This code creates a Request object with the specified URL, data, and headers, and then uses urlopen to send the request and get the response.

Note that in Python 2, urllib2 is used instead of urllib.request, and the Request class is used to create a request object.

In Python 3.x, urllib.request.Request is used to create a request object, and it’s much simpler to use. For example:

import urllib.request

url = "https://example.com"
headers = {"User-Agent": "My User Agent"}
data = "foo=bar&baz=qux"

req = urllib.request.Request(url, data.encode("utf-8"), headers)
response = urllib.request.urlopen(req)

print(response.read().decode("utf-8"))

This code creates a Request object with the specified URL, data, and headers, and then uses urlopen to send the request and get the response.

Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数