Python中可以使用标准库中的urllib或requests库来调用HTTP请求,下面分别介绍一下使用方法。

一、使用urllib库

  1. 发送GET请求

使用urllib库发送GET请求,可以使用urlopen方法,示例代码如下:

import urllib.request

response = urllib.request.urlopen('http://www.baidu.com')
html = response.read().decode('utf-8')
print(html)

其中,urlopen方法接受一个字符串类型的URL参数,返回一个类文件对象,可以使用read方法读取响应内容,需要指定字符集解码。

  1. 发送POST请求

使用urllib库发送POST请求,需要构造一个Request对象,并设置好请求头和请求体参数,示例代码如下:

import urllib.request
import urllib.parse

url = 'http://httpbin.org/post'
headers = {'User-Agent': 'Mozilla/5.0'}
data = {'name': 'Python', 'age': 20}
data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url=url, data=data, headers=headers)
response = urllib.request.urlopen(req)
html = response.read().decode('utf-8')
print(html)

其中,urlencode方法可以将字典类型的数据转换为URL编码的字符串类型,encode方法将字符串类型的数据转换为字节类型,Request对象的data参数需要传递字节类型的数据。

二、使用requests库

  1. 发送GET请求

使用requests库发送GET请求,可以使用get方法,示例代码如下:

import requests

response = requests.get('http://www.baidu.com')
html = response.text
print(html)

其中,get方法接受一个字符串类型的URL参数,返回一个Response对象,可以使用text属性获取响应内容。

  1. 发送POST请求

使用requests库发送POST请求,可以使用post方法,示例代码如下:

import requests

url = 'http://httpbin.org/post'
headers = {'User-Agent': 'Mozilla/5.0'}
data = {'name': 'Python', 'age': 20}
response = requests.post(url=url, data=data, headers=headers)
html = response.text
print(html)

其中,post方法的data参数可以传递字典类型的数据,headers参数需要传递一个字典类型的请求头。

在Python中调用HTTP请求

原文地址: https://www.cveoy.top/t/topic/bssQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录