首页 > 其他分享 >requests高级用法、代理池搭建、爬取某视频网站、爬取新闻

requests高级用法、代理池搭建、爬取某视频网站、爬取新闻

时间:2023-03-16 15:11:48浏览次数:41  
标签:http get res 用法 爬取 https print requests

目录

# 面试题
	-可变类型不可变类型
	- 你常用的魔法方法---》某种情况会自动触发
    	-__init__  类()--->对象进行初始化
        -__new__   类()---->产生对象---》触发__init__完成对象初始化
        -__call__  person=Person()--->对象加括号  person()---》触发
        -__getattr__  对象.属性,属性不存在,触发
        -__setattr__  对象.属性=值, 触发
        -__getitem__  对象['属性'],属性不存在,触发
        -__setitem__  对象['属性']=值, 触发
        -上下文管理器:只要重写了__enter__  __exit__ 方法,就具备这个能力
        	with 对象 as xx:
            	1 写了一行代码,触发__enter__的执行
            2 写了一行代码,触发__exit__,做一些资源清理工作
            
        -剩下的:https://www.cnblogs.com/liuqingzheng/articles/9949568.html
   - 类中的装饰器
	-classmethod
    -staticmethod
    -如何把方法包装成数据属性 propty装饰器
    -类中如何隐藏属性
    	__属性、方法
        
   -双写一致性
   -断点续传
    	-迅雷多线程下载
   -内网穿透:https://zhuanlan.zhihu.com/p/370483324
   -缓存击穿

image-20230316090057903

# 1 爬虫是什么
	-一个程序----》模拟发送http请求--->从网站,app,小程序---》获取数据---》清洗数据---》入库
    
# 2 爬虫的核心原理
	-发送http请求,解析数据
    -requests     re
    
# 3 requests模块---》大神---》基于python内置模块urllib3---》封装
	-python界非常知名的库
    -模拟发送http请求:postman也是发送http请求的
    
    -python GUI
    	-tkinter:内置模块
        -PyQT:python代码在qt平台写桌面应用
        
# 4 发送get请求,携带数据
	request.get(地址,params=get请求的数据)
    
# 5 发送请求请求头
	heaser={
        user-agent:
        cookies:
        referer
        
    }
	request.get(headers=heaser)
    
# 6 携带cookie 两种方式
	1 直接放在请求头中:字符串  cookies:xx=dsads;ee=sasdfa
    2 使用cookies参数request.get(cookies={}/cookieJar)

# 7 发送post请求
	request.post(,data,json)
# 8 requests.session()----->保持cookie,以后不用手动携带,自动处理
# 9 响应对象
	Response对象
    	-text
        -content
        -cookies
# 10 编码问题
# 11 获取二进制数据
	-下载图片,视频
    -response.iter_content()
    
    
# 6 http请求头
	-referer:是http请求头中的一个数据,记录从哪个页面跳转过来的
    	-图片防盗链
        -反扒

image-20230316092620833

1 requests高级用法

1.0 解析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)  # json 格式字符串---》json.cn
print(type(res.json()))  # 转成对象  字典对象

1.1 ssl认证(了解)

# http协议:明文传输
# https协议:http+ssl/tsl
	HTTP+ SSL / TLS,也就是在 http上又加了一层处理加密信息的模块,比 http安全,可防止数据在传输过程中被窃取、改变,确保数据的完整性
    https://zhuanlan.zhihu.com/p/561907474
        
# 以后遇到证书提示错误问题 ssl xxx
	1 不验证证书
    import requests
    respone=requests.get('https://www.12306.cn',verify=False) #不验证证书,报警告,返回200
    print(respone.status_code)
    
    2 关闭警告
    import requests
    from requests.packages import urllib3
    urllib3.disable_warnings() #关闭警告
    respone=requests.get('https://www.12306.cn',verify=False)
    print(respone.status_code)
    
    3 手动携带证书(了解)
    import requests
    respone=requests.get('https://www.12306.cn',
                         cert=('/path/server.crt',
                               '/path/key'))
    print(respone.status_code)

1.2 使用代理(重要)

# 如果爬虫使用自身ip地址访问,很有可能被封ip地址,以后就访问不了了

# 我们可以使用代理ip
# 代理:收费和免费(不稳定)


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

# res = requests.post('https://www.cnblogs.com',proxies={'http':'27.79.236.66:4001'})
res = requests.post('https://www.cnblogs.com',proxies={'http':'60.167.91.34:33080'})
print(res.status_code)



# 高匿代理和透明代理
	-高匿,服务端拿不到真实客户端的ip地址
    -透明:服务端能拿到真实客户端的ip地址
	
    -后端如何拿到真实客户端ip地址
    	-http请求头中有个:X-Forwarded-For: client1, proxy1, proxy2, proxy3
        -x-forword-for
        -获得HTTP请求端真实的IP

1.3 超时设置

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

1.4 异常处理

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')

1.5 上传文件

# 3 上传文件
import requests
files = {'file': open('美女.png', 'rb')}
respone = requests.post('http://httpbin.org/post', files=files)
print(respone.status_code)

2 代理池搭建

# requests 发送请求使用代理
# 代理从哪来
	-公司花钱买
    -搭建免费的代理池:https://github.com/jhao104/proxy_pool
        -python:爬虫+flask写的
        -架构:看下图
        
        
# 搭建步骤:
	1 git clone https://github.com/jhao104/proxy_pool.git
    2 使用pycharm打开
    3 安装依赖:pip install -r requirements.txt
    4 修改配置文件(redis地址即可)
        HOST = "0.0.0.0"
        PORT = 5010
        DB_CONN = 'redis://127.0.0.1:6379/0'
        PROXY_FETCHER #爬取哪些免费代理网站
   	5 启动爬虫程序
    python proxyPool.py schedule
	6 启动服务端
    python proxyPool.py server
    
    7 使用随机一个免费代理
    地址栏中输入:http://127.0.0.1:5010/get/
        
        
        
# 使用随机代理发送请求
import requests
from requests.packages import urllib3
urllib3.disable_warnings() #关闭警告
# 获取代理
res = requests.get('http://127.0.0.1:5010/get/').json()
proxies = {}
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)
# res = requests.post('https://www.cnblogs.com')
print(res)
        
        
      
        
        
        
        
        
        
        

image-20230316103529214

2.1 django后端获取客户端的ip

# 建立django后端---》index地址---》访问就返回访问者的ip


# django代码---》不要忘记改配置文件
# 路由
path('', index),
# 视图函数
def index(request):
    ip = request.META.get('REMOTE_ADDR')
    print('ip地址是', ip)
    return HttpResponse(ip)



# 测试端:

# import requests
# from requests.packages import urllib3
# urllib3.disable_warnings() #关闭警告
# # 获取代理
# res = requests.get('http://127.0.0.1:5010/get/').json()
# proxies = {}
# if res['https']:
#     proxies['https'] = res['proxy']
# else:
#     proxies['http'] = res['proxy']
#
# print(proxies)
# res=requests.get('http://101.43.19.239/', proxies=proxies,verify=False)
# print(res.text)


from threading import Thread
import requests


def task():
    res = requests.get('http://101.43.19.239/')
    print(res.text)


for i in range(10000000):
    t = Thread(target=task)
    t.start()

3 爬取某视频网站

import requests
import re

res = requests.get('https://www.pearvideo.com/category_loading.jsp?reqType=5&categoryId=1&start=0')
# print(res.text)
# 解析出真正视频地址
video_list = re.findall('<a href="(.*?)" class="vervideo-lilink actplay">', res.text)
# print(video_list)
for i in video_list:
    # i='video_1212452'
    video_id = i.split('_')[-1]
    real_url = 'https://www.pearvideo.com/' + i
    # print('真正视频地址是:',real_url)
    headers = {
        'Referer': 'https://www.pearvideo.com/video_%s' % video_id
    }
    res1 = requests.get('https://www.pearvideo.com/videoStatus.jsp?contId=%s&mrd=0.29636538326105044' % video_id,
                        headers=headers).json()
    # print(res1["videoInfo"]['videos']['srcUrl'])
    mp4_url = res1["videoInfo"]['videos']['srcUrl']
    mp4_url = mp4_url.replace(mp4_url.split('/')[-1].split('-')[0], 'cont-%s' % video_id)
    print(mp4_url)
    res2 = requests.get(mp4_url)
    with open('./video/%s.mp4' % video_id, 'wb') as f:
        for line in res2.iter_content():
            f.write(line)

# headers={
#     'Referer': 'https://www.pearvideo.com/video_1212452'
# }
# res=requests.get('https://www.pearvideo.com/videoStatus.jsp?contId=1212452&mrd=0.29636538326105044',headers=headers)
#
# print(res.text)


# https://video.pearvideo.com/mp4/short/20171204/    1678938313577    -11212458-hd.mp4
# https://video.pearvideo.com/mp4/short/20171204/     cont-1212452    -11212458-hd.mp4

mp4_url = 'https://video.pearvideo.com/mp4/short/20171204/  1678938313577-11212458-hd.mp4'

4 爬取新闻

import requests
# pip install beautifulsoup4   解析xml的库
from bs4 import BeautifulSoup

res = requests.get('https://www.autohome.com.cn/all/1/#liststart')
# print(res.text)
# 第一个参数是要解析的文本 str
# 第二个参数是:解析的解析器  html.parser:内置解析器       lxml:第三方需要额外安装
soup = BeautifulSoup(res.text, 'html.parser')
# 查找所有类名叫article的ul标签   find_all
ul_list = soup.find_all(name='ul', class_='article')
for ul in ul_list:
    li_list = ul.find_all(name='li')
    # print(len(li_list))
    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(name='img').attrs['src']
            print('''
            新闻标题:%s
            新闻连接:%s
            新闻摘要:%s
            新闻图片:%s
            ''' % (title, url, desc, img))


# 把所有图片下载到本地,把爬完的数据,存到mysql中---》pymysql---》commit

标签:http,get,res,用法,爬取,https,print,requests
From: https://www.cnblogs.com/bnmm/p/17222651.html

相关文章

  • python爬虫案列08:梨视频爬取一个短视频
    importrequestsfromlxmlimportetreeimportos#拿到视频地址urlurl='https://www.pearvideo.com/video_1160135'#提取url中的cont_id,后面用cont_id=url.sp......
  • 【python爬虫】 request模块介绍 http协议版本区别 双token认证 携带cookie的两种方
    目录上节回顾今日内容1爬虫介绍2request模块介绍3request发送get请求4request携带参数5url编码解码6携带请求头http协议版本之间的区别7发送post请求,携带数据对于......
  • importlib 用法
    首先看一下importlib.import_module(name,package=None)函数的参数函数调用存在两种方式:1.绝对导入,name为完整路径str,package为None。2.相对导入,package需指定对应包......
  • 爬虫-requests
    1.爬虫介绍爬虫就是程序从互联网中各个网站上爬取数据(只能爬区我们能看到的数据),然后进行数据清洗(筛选),入库。爬虫的本质:模拟http请求,获取数据,入库。百度就是一个大......
  • static用法
    一:如果两个方法都是普通方法,那么可以直接用方法名调用二:如果两个方法都是静态方法,那么可以直接用方法名调用三:如果在静态方法中调用非静态方法,那么需要先创建对象,再通......
  • 爬虫介绍、requests模块发送get请求、get请求携带参数、携带请求头、携带cookie、发送
    目录今日内容1爬虫介绍2requests模块发送get请求3get请求携带参数4携带请求头5携带cookie6发送post请求7响应Response8获取二进制数据9解析json#期终架构 -后......
  • django-filter用法
    一.环境准备pipinstallDjango==2.2-ihttps://pypi.douban.com/simplepipinstalldjangorestframework==3.10-ihttps://pypi.douban.com/simplepipinstalldjan......
  • Python range() 函数用法
    Python3range()返回的是一个可迭代对象(类型是对象),而不是列表类型,所以打印的时候不会打印列表函数语法range(start,stop[,step])参数说明:start:计数从start......
  • mysql merge update_SQL中批量更新 merge into用法
     从备份表中更新字段到正式表中,使用UPDATE批量更新大量的数据,会出现效率低下,有时候甚至卡死的情况,后面通过使用MERGEINTO代替UPDATE执行批量更新,会提升执行效率。......
  • nginx中proxy_pass各种用法详解
    代理转发规则nginx中配置location代理转发规则的时候不同写法对应不同转发规则。如果proxy_pass使用了URI,当传送请求到后端服务器时,规范化以后的请求路径与配置中的路径......