网络编程Python – HTTP 请求
HTTP代表超文本传输协议,它在客户端-服务器机器上工作。在大多数情况下,Web 浏览器充当客户端,托管网站的计算机充当服务器。 Python提供了 requests 模块来处理 HTTP 请求。 requests 模块在 HTTP 请求中起着主要作用,除了简单的请求和响应之外,它可以处理不同类型的 HTTP 通信,如身份验证、压缩、解压缩、分块请求等。
安装请求模块
在安装模块之前,请确保您的Python环境是最新的。之后安装pip并使用Python包管理器安装请求模块。
pip install requests
请求方法
request 模块提供了各种请求方法,用于对给定的Request-URI提供的资源执行操作。Methods Description delete(url, args) used to DELETE all the contents represented by the current target source of the specified URL. get(url, params, args) used to GET information from the server of a specified URL, it only retrieves data and does not affect other resources. head(url, args) it is the same as GET used transfers status line and header of the specified URL. patch(url, data, args) used to send a PATCH request to the URL. post(url, data, json, args) Used to POST data to the server specified by the URL. put(url, data, args) used to replace all the uploaded contents represented by the current target source of the specified URL. request(method, url, args) Used to REQUEST a specified method of the URL
下面是一个简单的Python HTTP 请求示例:
Python3
# Import library
import requests as req
# Requesting from server
r = req.get('https://www.geeksforgeeks.org/',)
# Getting the response code
print(r)
# Printing some lines of the request data
print(r.text[0:1000])
输出: