python爬虫---requests模块,response属性,代理,超时,认证,异常和上传文件

爬虫介绍


所有的软件,90%以上,cs,bs,主流都是用http协议通信,模拟发送http请求。服务端把数据返回(html,xml,json),数据的清洗(re,bs4),然后是入库(文件,mysql,redis,es,mongo)。

爬虫的本质:

1 模拟发送http请求(requests,requests-hmtl,selenium)
2 数据清洗反扒(re,bs4,lxml:css选择器,xpath选择器)
3 增加并发量(线程,进程,协程)---》scrapy
4 入库

# 最大的爬虫:百度,谷歌
-百度一刻不停的在互联网中爬取网页----》把网页存到百度的数据库
    	(基本上所有公司都希望被百度爬到,并且权重高,显示在最前面)----(seo,sem)
-当我们在搜索内容时,输入了关键字----》全文检索---》现在在搜索结果中

# 我们做爬虫要遵循爬虫协议:这个网站哪些让我们爬,哪些不让 -robots.txt

requests模块介绍


requests模块:模拟发送http请求。

urllib内置模块,可以发送http请求,但是api使用复杂。

介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3)

注意:requests库发送请求将网页内容下载下来以后,并不会执行js代码,这需要我们自己分析目标站点然后发起新的request请求。

安装

pip3 install requests

只能发送请求,不能解析html,后来作者又写了一个模块:requests-hmtl模块:兼具发送请求和解析:requests+lxml=requests-hmtl

不仅仅用来做爬虫,重点:后端跟另一个服务交互,也需要使用它.

import requests

# res=requests.get('https://www.cnblogs.com/')  # res是http响应封装成了对象,响应中得所有东西,都在这个对象中
# print(res.text)  # 响应体的字符串

携带get参数


方式一:直接使用

res=requests.get('https://www.cnblogs.com/?name=lqz&age=19')
print(res.text)  # 响应体的字符串

方式二:使用params参数

res=requests.get('https://www.cnblogs.com/',params={'name':'lqz','age':19})
print(res.text)  # 响应体的字符串

小注意:如果中文涉及到 url的编码和解码

from urllib import parse


res=parse.quote('李清照')
print(res)

res1=parse.unquote('%E6%9D%8E%E6%B8%85%E7%85%A7')
res1=parse.unquote('http://www.aa7a.cn/user.php?&ref=http%3A%2F%2Fwww.aa7a.cn%2Fuser.php%3Fact%3Dlogout')
print(res1)

携带请求头


携带请求头,某些网站爬不到是因为做了最初级的反扒,只要在请求头中添加user-agent参数即可,还有图片防盗链,还有除了首页外,上一个地址不是我们自己的地址,就禁掉。

常见请求头:

user-agent:客户端类型
Referer: https://www.lagou.com/gongsi/  上一次访问的地址

携带请求头:

header = {
     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',}
res=requests.get('https://dig.chouti.com/',headers=header)
print(res.text)

携带cookie


携带cookie---》登录信息---》携带着说明登录了---》能干登录的事

方式一:带在请求头中

 res = requests.post('https://dig.chouti.com/link/vote',
                     headers=header,
                     data={
                         'linkId': '35811284'
                     })

 print(res.text)

方式二:使用cookie参数:之前登录成功了,就有cookie,cookie是CookieJar的对象,直接传

 header = {
     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
 }
 requests.get()
 res = requests.post('https://dig.chouti.com/link/vote',
                     headers=header,
                     # Dict or CookieJar
                     # cookies={},
                     data={
                         'linkId': '35811284'
                    })

 print(res.text)

post请求


发送post请求---》登录接口

from-data,urlencoded(默认),json
 res = requests.post('http://www.aa7a.cn/user.php', data={
     'username': '@qq.com',
     'password': '',
     'captcha': 'aaaa',
     'remember': 1,
     'ref': 'http://www.aa7a.cn/user.php?act=logout',
     'act': ' act_login',
 })
 print(res.text)
 print(res.cookies)  # 登录成功的cookie,cookieJar对象--》字典
 # 登录成功
 res1=requests.get('http://www.aa7a.cn/',cookies=res.cookies)
 print('616564099@qq.com' in res1.text)

post请求携带数据


# 6 post请求编码是json格式
# res=requests.post('xxx',json={})

request.session


request.session的使用,整个过程中自动维护cookie。

 session=requests.session()
 # 使用session发送请求
 session.post('http://www.aa7a.cn/user.php', data={
     'username': '616564099@qq.com',
     'password': 'lqz123',
     'captcha': 'aaaa',
     'remember': 1,
     'ref': 'http://www.aa7a.cn/user.php?act=logout',
     'act': ' act_login',
 })
 res1=session.get('http://www.aa7a.cn/')
 print('616564099@qq.com' in res1.text)

response属性


repsonse对象的属性和方法:把http的响应封装成了response。

respone=requests.get('https://www.cnblogs.com/')
respone=requests.get('http://www.autohome.com/news')
# print(respone.text)   # 响应体的字符串
# print(respone.content) # 响应体二进制数据
# print(respone.status_code) #响应状态码
# print(respone.headers)# 响应头
# print(respone.cookies) #响应的cookie
# print(respone.cookies.get_dict()) #cookie转成dict
# print(respone.cookies.items())  # cookie拿出key和value
# print(respone.url)         # 请求的地址
# print(respone.history)     # 列表,有重定向,里面放了重定向之前的地址
# print(respone.encoding)   # 响应编码格式
# 后期咱们下载图片,视频,需要使用它
# respone.iter_content()

编码问题


编码问题:大部分网站都是utf-8编码,老网站中文编码使用gbk,gb2312

 respone = requests.get('http://www.autohome.com/news')
 # respone.encoding='gbk'
 print(respone.text)  # 默认使用utf-8可能会导致中文乱码

获取二进制数据


 response.content
 response.iter_content(chunk_size=1024)
 res=requests.get('https://gd-hbimg.huaban.com/e1abf47cecfe5848afc2a4a8fd2e0df1c272637f2825b-e3lVMF_fw658')
 with open('美女.png','wb') as f:
     f.write(res.content)

解析json


res = requests.post('http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword', data={
    'cname': '',
    'pid': '',
    'keyword': '北京',
    'pageIndex': 1,
    'pageSize': 10,

})
print(res.text)
print(type(res.text))
import json

dic_res = json.loads(res.text)
print(type(dic_res))
print(dic_res['Table1'][0]['storeName'])

# 简便方法
 res = requests.post('http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword', data={
     'cname': '',
     'pid': '',
    'keyword': '北京',
     'pageIndex': 1,
     'pageSize': 10,

 })
 print(type(res.json()))
 print(type(res.json()))

高级用法之 Cert Verification


高级用法之证书(了解)----》http请求---》https请求

什么是https=http+ssl

发送请求手动携带证书

 # 不验证证书,直接访问
 respone=requests.get('https://www.12306.cn',verify=False)
 respone=requests.get('https://www.12306.cn',
                      cert=('/path/server.crt',
                            '/path/key'))

代理


频率限制,限制ip,黑名单(封ip)可以通过代理解决。

 import requests
 proxies = {
     'http': '112.14.47.6:52024',
 }
 #180.164.66.7
 respone=requests.get('https://www.cnblogs.com/',proxies=proxies)
 print(respone.status_code)

 # django---》部署到云服务器上---》客户端ip --request.META.get('REMOTE_ADDR')

超时,认证,异常,上传文件


超时设置

 import requests
 respone=requests.get('https://www.baidu.com',timeout=0.0001)

异常处理

from requests.exceptions import *
 try:
     r=requests.get('http://www.baidu.com',timeout=0.00001)
 # except ReadTimeout:
 #     print('===:')
 # except ConnectionError: #网络不通
 #     print('-----')
 # except Timeout:
 #     print('aaaaa')
 except Exception:
     print('x')

上传文件

 import requests
 files={'file':open('a.jpg','rb')}
 respone=requests.post('http://httpbin.org/post',files=files)
 print(respone.status_code)
posted @   早安_1207  阅读(455)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
返回顶端
点击右上角即可分享
微信分享提示