How to use the urllib.request.urlopen() function to send a GET request in Python 3.x
In network programming, we often need to obtain data from the remote server by sending HTTP requests. In Python, we can use the urllib.request.urlopen() function in the urllib module to send an HTTP request and get the response returned by the server. This article will describe how to use this function to send GET requests.
First, we need to import the urllib.request module:
import urllib.request
Next, we can use the urllib.request.urlopen() function to send a GET request. This function accepts a URL parameter of type string and returns a response object similar to a file object. We can use the read() method of this object to read the data returned by the server.
The following is a sample code that demonstrates how to use the urllib.request.urlopen() function to send a GET request and obtain the data returned by the server:
import urllib.request def send_get_request(url): # 发送 GET 请求 response = urllib.request.urlopen(url) # 读取服务器返回的数据 data = response.read() # 将返回的数据转换为字符串并打印 print(data.decode('utf-8'))
In the above code, the send_get_request() function Accepts a string type URL parameter, then uses the urllib.request.urlopen() function to send a GET request and prints the returned data to the console.
We can call the send_get_request() function to send a GET request, as shown below:
url = 'http://www.example.com' send_get_request(url)
The above code will send a GET request to http://www.example.com, and then print the server The data returned.
It should be noted that the return value of the urllib.request.urlopen() function is a response object similar to a file object. We can obtain other information returned by the server by calling some methods of this object, such as Response code, response header, etc. The following is a sample code to obtain the response code and response header:
import urllib.request def send_get_request(url): # 发送 GET 请求 response = urllib.request.urlopen(url) # 打印响应码 print('Response Code:', response.getcode()) # 打印响应头 print('Response Headers:', response.getheaders()) # 读取服务器返回的数据 data = response.read() # 将返回的数据转换为字符串并打印 print(data.decode('utf-8'))
Summary
This article introduces how to use the urllib.request.urlopen() function to send a GET request and obtain the response returned by the server. data. By calling this function, we can easily send a request to the remote server and get the response. At the same time, we can also obtain other information such as response code and response header by calling the method of the response object. I hope this article will be helpful to everyone when using Python for network programming.
The above is the detailed content of How to use the urllib.request.urlopen() function to send a GET request in Python 3.x. For more information, please follow other related articles on the PHP Chinese website!