首页 > 其他分享 >requests高级用法

requests高级用法

时间:2023-03-16 20:00:33浏览次数:66  
标签:res 代理 高级 https import requests 用法 com

爬虫requests高级用法

解析json

发送http请求返回的数据有xml格式也会有json格式

import requests
data = {
    'cname': '',
    'pid': '',
    'keyword': '500',
    'pageIndex': 1,
    'pageSize': 10
}
res= requests.post('http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword',data=data)
print(res.text)  
print(=res.json())  # 封装了json不需要再导json模块

ssl认证(可能面试会问)

http与https的区别

http协议是明文传输安全性低 80端口

https http + ssl + tsl 443端口

httsps 是在http协议上又加了一层处理加密信息的模块,比http安全,可防止数据在传输过程中被窃取,改变。确保数据完整性。

ssl 安全套接字层,SSL协议位于tcp、IP协议与各种应用层协议之间。为数据通信提供安全支持

TLS 传输层安全,由于存在安全漏洞,已经很少被使用到。发展至今已经有 TLS 1.0、TLS 1.1、TLS 1.2 三个版本,TLS 1.3 改动会比较大,目前还在草案阶段,目前使用最广泛的是TLS 1.1、TLS 1.2

详细文档 https://zhuanlan.zhihu.com/p/561907474

如果遇到证书提示错误问题(ssl,xxx 就是)

解决方法

不验证证书 verify=False

import requests
respone=requests.get('https://www.12306.cn',verify=False) #不验证证书,报警告,返回200
print(respone.status_code)

关闭警告

import requests
from requests.packages import urllib3
urllib3.disable_warnings() #关闭警告
respone=requests.get('https://www.12306.cn',verify=False)
    print(respone.status_code)

手动携带证书

import requests
respone=requests.get('https://www.12306.cn',
           cert=('/path/server.crt', # 证书
                  '/path/key')) # 公钥
print(respone.status_code)

代理

如果爬虫使用自身ip地址访问,很有可能会被封。可以使用ip代理

1. 正向代理

1.1 概念

正向代理是一个位于客户端和目标服务器之间的代理服务器(中间服务器)。为了从目标服务器取得内容,客户端向代理服务器发送一个请求,并且指定目标服务器,之后代理向目标服务器转发请求,将获得的内容返回给客户端。正向代理的情况下,客户端必须要进行一些特殊的设置才能使用。

1.2 特点
  • 正向代理需要主动设置代理服务器 ip 或者域名进行访问,由设置的服务器 ip 或者域名去访问内容并返回
  • 正向代理是代理客户端,为客户端收发请求,使真实客户端对服务器不可见。

2. 反向代理

2.1 概念

反向代理是指以代理服务器来接收客户端的请求,然后将请求转发给内部网络上的服务器,将从服务器上得到的结果返回给客户端,此时代理服务器对外表现为一个反向代理服务器。

对于客户端来说,反向代理就相当于目标服务器,只需要将反向代理当作目标服务器一样发送请求就可以了,并且客户端不需要进行任何设置。

2.2 特点
  • 正向代理需要配置代理服务器,而反向代理不需要做任何设置。
  • 反向代理是代理服务器,为服务器收发请求,使真实服务器对客户端不可见。

requests 使用ip代理

res =requests.post('https://www.cnblogs.com',proxies={'http/https':'地址:端口'})

# 代理ip可以在网上寻找
res = requests.post('https://www.cnblogs.com',proxies={'http':'60.167.91.34:33080'})
print(res.status_code)

代理的种类

高匿代理
服务端只能看到代理,拿不到客户端真实的ip
透明代理
服务端能拿到真实客户端的ip地址

后端如何拿到真实客户端ip地址

# http请求头中有个:XFF
X-Forwarded-For: client1, proxy1, proxy2, proxy3

超时设置

超出时间直接断开链接

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

异常处理

就是用try包起来

import requests
from requests.exceptions import * #可以查看requests.exceptions获取异常类型
try:    r=requests.get('http://www.baidu.com',timeout=0.00001)
except ReadTimeout:
    print('===:')
# except ConnectionError: #网络不通
#     print('-----')
# except Timeout:
#     print('aaaaa')

except RequestException:
    print('Error')
    
  "直接使用Exception吧"

上传文件

"上传文件可以写个脚本传"
import requests
files = {'file': open('美女.png', 'rb')}
respone = requests.post('http://httpbin.org/post', files=files)
print(respone.status_code)

代理池搭建

1.花钱买

2.搭建免费的代理池

https://github.com/jhao104/proxy_pool python:爬虫+flask写的

搭建步骤

git clone https://github.com/jhao104/proxy_pool.git

使用pycharm打开

安装依赖:pip install -r requirements.txt

修改配置文件settings(redis地址即可)

HOST = "0.0.0.0"
PORT = 5010
DB_CONN = 'redis://127.0.0.1:6379/0'
PROXY_FETCHER #爬取哪些免费代理网站

启动爬虫程序

python proxyPool.py schedule

启动服务端

python proxyPool.py server

编写脚本

import requests
# 往代理池发送请求 获取代理ip
res = requests.get('http://192.168.1.206:5010/get/').json()
# 关闭警告
from requests.packages import urllib3
urllib3.disable_warnings()
proxies = {}
# 如果能取迟来https说明是https
if res['https']:
    proxies['https'] = res['proxy']
else:
    proxies['http'] = res['proxy']
print(proxies)
res = requests.post('https://www.cnblogs.com',proxies=proxies,verify=False)
print(res)

django后端获取ip

ip= request.META.get('REMOTE_ADDR')

实操

爬取某视频网站

import re

import requests
from requests.packages import urllib3
urllib3.disable_warnings()
res = requests.get('https://www.pearvideo.com/category_loading.jsp?reqType=5&categoryId=1&start=2',verify=False)

# 解析出真正的地址
video_list=re.findall('<a href="(.*?)" class="vervideo-lilink actplay">',res.text)
for i in video_list:

    # 拿出视频id
    video_id = i.split('_')[-1]
    # 拼接真实地址
    real_url = 'https://www.pearvideo.com/'+i
    heads = {
        'Referer': f'https://www.pearvideo.com/video_{video_id}'
        }
    res1 = requests.get(f'https://www.pearvideo.com/videoStatus.jsp?contId={video_id}&mrd=0.44340819553576494',
                        headers=heads).json()
    # 通过观察返回结果得知视频链接是在res1['videoInfo']['videos']['srcUrl']里
    mp4_url=res1['videoInfo']['videos']['srcUrl']
    # 拿出来的链接,还是不能访问,回到网站观察标签和我们生成出来的地址作对比发现。
    # https://video.pearvideo.com/mp4/short/20171204/    1678938313577    -11212458-hd.mp4
	# https://video.pearvideo.com/mp4/short/20171204/     cont-1212452    -11212458-hd.mp4
    # 对数据做处理
    ret=mp4_url.replace(mp4_url.split('/')[-1].split('-')[0],f'cont-{video_id}')
    print(ret)

爬取新闻

import requests
for i in range(1,100):
    res = requests.get(f'https://www.autohome.com.cn/all/{i}/#liststart')
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(res.text,'html.parser')
    # 找到属性为article的ul标签
    ul_list = soup.find_all(name='ul',class_='article')
    for ul in ul_list:
        li_list = ul.find_all(name='li')
        for li in li_list:
            h3 = li.find(name='h3')
            if h3:
                title = h3.text
                url = 'https:' + li.find('a').attrs['href']
                desc = li.find('p').text
                img =  li.find('img').attrs['src']
                if 'https:' not in img:
                    img= 'https:'  + img
                print(f"""
                新闻标题:{title},
                新闻链接:{url},
                新闻标题:{desc},
                新闻图片:{img}
                """)

标签:res,代理,高级,https,import,requests,用法,com
From: https://www.cnblogs.com/LiaJi/p/17223943.html

相关文章