python编程实践:网络爬虫,从学习Requests 模块开始

python编程实践:网络爬虫,从学习Requests 模块开始

编程文章jaq1232025-05-09 6:12:238A+A-

Requests模块是第三方模块,需要预先安装,requests模块在python内置模块的基础上进行了高度的封装,从而使得python进行网络请求时,变得更加简洁和人性化。

我们都知道爬虫模拟浏览器发送请求,获取响应,那么首先我们就要学会使用Requests的基本方法和发送请求。

一、安装

非常简单,打开cmd,直接pip安装,

pip install requests

二、导入模块

import requests

三、requests库的七个主要方法

方法

解释

requests.request()

构造一个请求,支持以下各种方法

requests.get()

获取html的主要方法

requests.head()

获取html头部信息的主要方法

requests.post()

向html网页提交post请求的方法

requests.put()

向html网页提交post请求的方法

requests.patch()

向html提交局部修改的请求

requests.delete()

向html提交删除请求

在实际使用中,使用频率高的1-5项。

四、简单使用

(一)Get 请求

1. 发送无参数的get请求,尝试获取某个网页.

r = requests.get('http://www.baidu.com')

发送无参数的get请求 设置超时时间 timeout 单位秒

r = requests.get('http://www.baidu.com', timeout=1)

2.发送带参数的请求.

也许经常想为 URL 的查询字符串(query string) 传递某种数据。如果你是手工构建 URL,那么数据会以键/值对的形式置于 URL 中,跟在一个问号的后面。

例如: www.baidu.com/?key=val。

Requests 允许你使用 params 关键字参数,以一个字符串字典来提供这些参数。

举例来说,如果你想传递 key1=value1 和 key2=value2 到 www.baidu.com/ ,那么你可以使用如下代码:

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("https://www.baidu.com/", params=payload)
print(r.url)
#https://www.baidu.com/?key2=value2&key1=value1

以上代码相当于浏览器请求地址:https://www.baidu.com/?key2=value2&key1=value1

你还可以将一个列表作为值传入.

payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('http://www.baidu.com/', params=payload)
print(r.url)
#http://www.baidu.com/?key2=value2&key2=value3&key1=value1

以上代码相当于浏览器请求地址:http://www.baidu.com/?key2=value2&key2=value3&key1=value1

3.定制请求头

如果你想为请求添加 HTTP 头部,只要简单地传递一个 dict 给 headers 参数就可以了

url = 'https://www.baidu.com/s?wd=python'
headers = {
'Content-Type': 'text/html;charset=utf-8',
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
}
r = requests.get(url,headers=headers)

4.Response对象使用

  • r.url #打印输出该 URL
  • r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
  • r.status_code #返回连接状态,200正常。
  • r.text #默认以unicode形式返回网页内容,也就是网页源码的字符串。
  • r.content #以字节形式(二进制)返回。字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩。
  • r.json() #把网页中的json数据转成字典并将其返回。
  • r.encoding #获取当前的编码
  • r.encoding = 'ISO-8859-1' #指定编码,r.text返回的数据类型,写在r.text之前。

(二)POST 请求

HTTP 协议规定 POST 提交的数据必须放在消息主体(entity-body)中,但协议并没有规定数据必须使用什么编码方式,服务端通过是根据请求头中的Content-Type字段来获知请求中的消息主体是用何种方式进行编码,再对消息主体进行解析。具体的编码方式包括:

1.最常见post提交数据的方式,以form表单形式提交数据。

application/x-www-form-urlencoded

2.以json串提交数据。

application/json

3.一般使用来上传文件。

multipart/form-data

(三)实例如下

1. 以form形式发送post请求

Reqeusts支持以form表单形式发送post请求,只需要将请求的参数构造成一个字典,然后传给requests.post()的data参数即可

payload = {'key1': 'value1','key2': 'value2'}
r = requests.post("http://www.bin.org/post", data=payload)
print(r.text)

2. 以json形式发送post请求

可以将一 json串传给requests.post()的data参数,

url = 'http://www.bin.org/post'
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post(url, data=json.dumps(payload))
#print(r.text)
print(r.headers.get('Content-Type'))

3. 以multipart形式发送post请求

Requests也支持以multipart形式发送post请求,只需将一文件传给requests.post()的files参数即可,文本文件report.txt的内容只有一行:Hello world!,从请求的响应结果可以看到数据已上传到服务端中。

url = 'http://www.bin.org/post'
files = {'file': open('report.txt', 'rb')}
r = requests.post(url, files=files)
print(r.text)

五、综合举例

1.返回值为json格式

import requests 
response = requests.get(url="http://xx.xx.xx/api/test123")
response.raise_for_status()
data = response.json()
print(data)

2.post方式请求,参数以json格式传递

import requests
import json
 d= {
    "app_name": "test123",
    "system_name": "test123",
    "instance_id": "test123",
    "resource_name": "test123",
    "env_region": "test123",
    "status": 0
} 
header = {"content-type":"application/json"} 
data = json.dumps(d)
response = requests.post(url="http://xx.xx.xx/api/add/", data=data, headers=header) 
print(response.text)

3.put方式请求,参数以json格式传递

import requests
import json 
d= {
    "app_name": "test126",
    "system_name": "test126",
    "instance_id": "test126",
    "resource_name": "test126",
    "env_region": "test126",
    "status": 0
} 
header = {"content-type":"application/json"} 
data = json.dumps(d)
response = requests.put(url="http://xx.xx.xx/api/update/test123/", data=data, headers=header)
 print(response.text)

4.delete方式请求

import requests 
response = requests.delete(url="http://127.0.0.1:8000/api/delete/test126")
response.raise_for_status()
data = response.json()
print(data)

需要说明的一点,使用什么方式请求服务,与服务器程序的定义有很大的关系,参数的传递方式,也与服务器程序的定义有关,至于更细的细节,也与服务器程序的编写语言有关。

这些知识点,与大家所认为的“爬虫”有关。后面有时间会给大家进一步阐述网络“爬虫”的案例。

最后,由于平台规则,只有当您跟我有更多互动的时候,才会被认定为铁粉。如果您喜欢我的文章,可以点个“关注”,成为铁粉后能第一时间收到文章推送。

点击这里复制本文地址 以上内容由jaq123整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!

苍茫编程网 © All Rights Reserved.  蜀ICP备2024111239号-21