爬虫简介

1 爬虫介绍

# 所有的软件,90%以上,cs,bs,主流都是用http协议通信,模拟发送http请求---》服务端把数据返回(html,xml,json)---->数据的清洗(re,bs4)---->入库(文件,mysql,redis,es,mongo)
	-mysql:tcp自定定制的协议
    -redis:tcp自定定制的协议
    -docker:http协议,符合resful规范
    -es:http协议,符合resful规范

# 爬虫的本质:
	1 模拟发送http请求(requests,requests-hmtl,selenium)
    2 数据清洗反扒(re,bs4,lxml:css选择器,xpath选择器)
    3 增加并发量(线程,进程,协程)---》scrapy
    4 入库
    
# 最大的爬虫:百度,谷歌
	-百度一刻不停的在互联网中爬取网页----》把网页存到百度的数据库
    	(基本上所有公司都希望被百度爬到,并且权重高,显示在最前面)----(seo,sem)
    -当我们在搜索内容时,输入了关键字----》全文检索---》现在在搜索结果中


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


# 编码,混淆,加密的区别
# js逆向,安卓反编译,动态调试(汇编)

2 requests模块介绍

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

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

# 安装:pip3 install requests
# 只能发送请求,不能解析html,后来作者又写了一个模块:requests-hmtl模块:兼具发送请求和解析
	requests+lxml=requests-hmtl
    
    
# 不仅仅用来做爬虫,重点:后端跟另一个服务交互,也需要使用它
	-假设公司有:短链系统    把很长的url链接生成短的url链接
    	-原理:申请很短的域名:https://sourl.cn/wBdfzc
        	id    code        url
            1     wBdfzc     https://image.baidu.com/search/index?
            
    -其它系统生成的链接很长---》转短---》调用短链系统的接口
import requests

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

3 携带get参数

# 2 请求地址中带参数
# 方式一:直接使用
# 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的编码和解码
# https://www.cnblogs.com/?name=%E6%9D%8E%E6%B8%85%E7%85%A7&age=19
#                              %E6%9D%8E%E6%B8%85%E7%85%A7
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)

4 携带请求头

# 3 携带请求头
# 爬不到---》做了反扒————》最初级的反扒----》现在请求头中得user-agent
# 常见请求头:
# user-agent:客户端类型
# Referer: https://www.lagou.com/gongsi/  上一次访问的地址
# 图片防盗链
# 反扒:除了首页外,上一个地址不是我们自己的地址,就禁掉


# 面试题:讲讲你知道的http的请求头? x-forword-for
# 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)

5 携带cookie

# 4 携带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)

6 post请求

# 5 发送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)

7 post请求携带数据

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

8 request.session

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

9 response属性

# 8 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()

# res=requests.get('https://video.pearvideo.com/mp4/adshort/20220427/cont-1760318-15870165_adpkg-ad_hd.mp4')
# with open('致命诱惑3.mp4','wb') as f:
#     # f.write(res.content)
#     for line in res.iter_content(chunk_size=1024): # 按1024字节写
#         f.write(line)

10 编码问题

# 9 编码问题---》大部分网站都是utf-8编码,老网站中文编码使用gbk,gb2312
# respone = requests.get('http://www.autohome.com/news')
# # respone.encoding='gbk'
# print(respone.text)  # 默认使用utf-8可能会导致中文乱码

11 获取二进制数据

# 10 获取二进制数据
# 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)

11 解析json

# 11 解析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,
#
# })# 11 解析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()))

13高级用法之 Cert Verification

# 13 高级用法之证书(了解)----》http请求---》https请求
# 什么是https=http+ssl
# 发送请求手动携带证书
# import requests
# # 不验证证书,直接访问
# respone=requests.get('https://www.12306.cn',verify=False)
# respone=requests.get('https://www.12306.cn',
#                      cert=('/path/server.crt',
#                            '/path/key'))

14 代理

# 14 代理---》频率限制---》限制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')

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

# 15 超时设置
# import requests
# respone=requests.get('https://www.baidu.com',timeout=0.0001)


# 16 异常处理
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')


# 17 上传文件
# import requests
# files={'file':open('a.jpg','rb')}
# respone=requests.post('http://httpbin.org/post',files=files)
# print(respone.status_code)
posted @ 2022-07-31 14:32  thrombus  阅读(142)  评论(0编辑  收藏  举报