首页 > 其他分享 >爬虫学习-01

爬虫学习-01

时间:2022-11-23 19:58:13浏览次数:42  
标签:01 请求 get res 爬虫 学习 cookie print requests

一、爬虫介绍

爬虫(spider):网络蜘蛛

本质原理:

  • 现在所有的软件原理:大部分都是基于http请求发送和获取数据的
    • PC端的网页
    • 移动端app
  • 模拟发送http请求,从别人的服务端获取数据
  • 绕过反扒:不同程序反扒措施不一样,比较复杂

爬虫原理

  • 发送http请求【requests,selenium】——>第三方服务端——>服务端响应的数据解析出想要的数据【selenium,bs4】——>入库(文件、excel、mysql、redis、mongodb)
  • scrapy:专业的爬虫框架

爬虫是否合法

  • 爬虫协议:每个网站根路径下都有 robots.txt,这个文件规定了该网站哪些可以爬取哪些不能爬

百度:其实就个“大爬虫”

  • 百度搜索框中输入 搜索内容,回车,返回的数据,是百度数据库中的数据
  • 百度一刻不停的在互联网中爬取每个页面,爬出来链接地址——>爬完存在自己的数据库
  • 当你点击,跳转到真正的地址上去了
  • 核心:搜索,海量数据中搜索出来想要的数据
  • seo:免费的搜索,排名靠前
  • sem:花钱买关键字,打广告拍的靠前

二、requests模块发送get请求

模拟发送http请求的模块:requests不仅仅爬虫用它,后期调用第三方接口,也是要用它的

  • 下载:pip install requests
    • 本质是封装了内置模块 urlib3

代码展示

  • 发送get请求 返回http响应体的文本内容,然后从返回内容里解析你想要的数据
import requests

res = requests.get('https://www.cnblogs.com/zzjjpp/')
print(res.text)

三、get请求携带参数

  • 发送get请求携带数据
    • 在地址栏中拼接
# 2 发送get请求携带数据
# 2.1 地址栏中拼接
# res=requests.get('https://www.baidu.com/s?wd=%E7%BE%8E%E5%A5%B3')
# print(res.text)
  • 使用params参数携带
# 2.2 使用params参数携带
# res=requests.get('https://www.baidu.com/s',params={
#     'wd':'球员',
#     'name':'curry'
# })
# print(res.text)
# https://www.baidu.com/s?wd=球员&name=curry

url编码和解码

  • 使用内置模块 urllib里的 parse进行编码和解码
from urllib import parse

res = parse.quote('球员')
print(res)
res = parse.unquote('%E7%90%83%E5%91%98')
print(res)

四、携带请求头

http请求:有请求头   有的网站,通过某些请求头来做反扒

请求头中带数据——>爬取某个网站,不能正常返回,因为模拟的不像

网站做反扒,没有携带请求头中的客户端类型

User-Agent:客户端类型:有浏览器、手机浏览器、爬虫类型、程序、scrapy...一般未造成浏览器

请求头里有referer:上次访问的地址:Referer: https://www.lagou.com/gongsi/

  • 如果要登录,模拟向登录接口发post请求,正常操作必须在登录页面上才可以做,如果没有携带referer,它就认为你是恶意的,给你禁止掉
  • 图片防盗链
  • 认证后给的cookie相当于登录了
# 请求头中带数据
# 网站做反扒,没有携带请求头
header = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
}
res = requests.get('https://dig.chouti.com/',headers=header)
print(res.text)

五、携带cookie

  • 方式一:直接带在请求头中
  • 方式二:通过cookie参数:因为cookie很特殊,一般都需要携带,模块把cookie单独抽取成一个参数,是字典类型,以后可以通过参数传入
方式一:直接带在请求头中

模拟点赞
# data={
#     'linkId':'36996038'
# }
# header={
#     # 客户端类型
#     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',
#     #携带cookie
#     'Cookie':'deviceId=web.eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqaWQiOiI3MzAyZDQ5Yy1mMmUwLTRkZGItOTZlZi1hZGFmZTkwMDBhMTEiLCJleHBpcmUiOiIxNjYxNjU0MjYwNDk4In0.4Y4LLlAEWzBuPRK2_z7mBqz4Tw5h1WeqibvkBG6GM3I; __snaker__id=ozS67xizRqJGq819; YD00000980905869%3AWM_TID=M%2BzgJgGYDW5FVFVAVQbFGXQ654xCRHj8; _9755xjdesxxd_=32; Hm_lvt_03b2668f8e8699e91d479d62bc7630f1=1666756750,1669172745; gdxidpyhxdE=W7WrUDABQTf1nd8a6mtt5TQ1fz0brhRweB%5CEJfQeiU61%5C1WnXIUkZH%2FrE4GnKkGDX767Jhco%2B7xUMCiiSlj4h%2BRqcaNohAkeHsmj3GCp2%2Fcj4HmXsMVPPGClgf5AbhAiztHgnbAz1Xt%5CIW9DMZ6nLg9QSBQbbeJSBiUGK1RxzomMYSU5%3A1669174630494; YD00000980905869%3AWM_NI=OP403nvDkmWQPgvYedeJvYJTN18%2FWgzQ2wM3g3aA3Xov4UKwq1bx3njEg2pVCcbCfP9dl1RnAZm5b9KL2cYY9eA0DkeJo1zfCWViwVZUm303JyNdJVAEOJ1%2FH%2BJFZxYgMVI%3D; YD00000980905869%3AWM_NIKE=9ca17ae2e6ffcda170e2e6ee92bb45a398f8d1b34ab5a88bb7c54e839b8aacc1528bb8ad89d45cb48ae1aac22af0fea7c3b92a8d90fcd1b266b69ca58ed65b94b9babae870a796babac9608eeff8d0d66dba8ffe98d039a5edafa2b254adaafcb6ca7db3efae99b266aa9ba9d3f35e81bdaea4e55cfbbca4d2d1668386a3d6e1338994fe84dc53fbbb8fd1c761a796a1d2f96e81899a8af65e9a8ba3d4b3398aa78285c95e839b81abb4258cf586a7d9749bb983b7cc37e2a3; token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqaWQiOiJjZHVfNTMyMDcwNzg0NjAiLCJleHBpcmUiOiIxNjcxNzY1NzQ3NjczIn0.50e-ROweqV0uSd3-Og9L7eY5sAemPZOK_hRhmAzsQUk; Hm_lpvt_03b2668f8e8699e91d479d62bc7630f1=1669173865'
# }
# res=requests.post('https://dig.chouti.com/link/vote',data=data,headers=header)
# print(res.text)


方式二:通过cookie参数:因为cookie很特殊,一般都需要携带,模块把cookie单独抽取成一个参数,是字典类型,以后可以通过参数传入

data={
    'linkId':'36996038'
}
header={
    # 客户端类型
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',
}
res=requests.post('https://dig.chouti.com/link/vote',data=data,headers=header,cookies={'key':'value'})
print(res.text)

 补充

# 部署项目出现的可能的问题
	-路径问题:ngxin,uwsgi。。。
    -数据库用户名密码问题
    -前端发送ajax请求问题
    -浏览器中访问一下banner接口
    	-nginx 8080    
        -安全组 80  8080 3306
        -转到uwsgi的8888,视图类
        
    -虚拟环境真实环境都要装uwsgi
    -启动uwsgi是在虚拟环境中启动的

 六、发送post请求

# data = {
#     'username': '[email protected]',
#     'password': 'curry',
#     'captcha': 'aaaa',
#     'remember': 1,
#     'ref': 'http://www.aa7a.cn/',
#     'act': 'act_login'
# }
# res = requests.post('http://www.aa7a.cn/user.php', data=data)
# print(res.text)
# print(res.cookies)  # 响应头中得cookie,如果正常登录,这个cookie 就是登录后的cookie  RequestsCookieJar:当成字典
#
访问首页,带着登录的cookies访问,
# # res2 = requests.get('http://www.aa7a.cn/', cookies=res.cookies)
# print('[email protected]' in res2.text)

6.3 post请求携带数据 data={} ,json={}   drf后端,打印 request.data
# data=字典是使用默认编码格式:urlencoded
# json=字典是使用json 编码格式
# res = requests.post('http://www.aa7a.cn/user.php', json={})

6.4 request.session的使用:当request使用,但是它能自动维护cookie
再发送请求用session发
# session=requests.session()
# data = {
#     'username': '[email protected]',
#     'password': 'curry',
#     'captcha': 'aaaa',
#     'remember': 1,
#     'ref': 'http://www.aa7a.cn/',
#     'act': 'act_login'
# }
# res = session.post('http://www.aa7a.cn/user.php', data=data)
# res2 = session.get('http://www.aa7a.cn/')
# print('[email protected]' in res2.text)

七、响应Response 

Response对象:有很多属性和方法

response属性
text 响应体的文本内容
content 响应体的二进制内容
status_code 响应状态码
headers 响应头
cookies 响应cookie
cookies.get_dict() cookieJar对象,获得到真正的字段
cookies.items() 获得cookie的所有key和value值
url 请求地址
history 问这个地址,可能会重定向,放了它冲定向的地址
encoding 页面编码
import requests

header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',
}
respone = requests.get('https://www.jianshu.com', params={'name': 'curry', 'age': 33},headers=header)
# respone属性
print(respone.text)  # 响应体的文本内容
print(respone.content)  # 响应体的二进制内容
print(respone.status_code)  # 响应状态码
print(respone.headers)  # 响应头
print(respone.cookies)  # 响应cookie
print(respone.cookies.get_dict())  # cookieJar对象,获得到真正的字段
print(respone.cookies.items())  # 获得cookie的所有key和value值
print(respone.url)  # 请求地址
print(respone.history)  # 访问这个地址,可能会重定向,放了它冲定向的地址
print(respone.encoding)  # 页面编码

 八、获取二进制数据

获取二进制数据:图片、视频

 图片保存到本地 

res = requests.get(
    'https://img.mp.itc.cn/q_70,c_zoom,w_640/upload/20161030/e5346e33e02040a6afbd354dbb4052a5_th.jpeg')
with open('库里.jpeg', 'wb') as f:
    f.write(res.content)

但是如果非常大,内存直接崩了,可以一段一段的写 

九、解析json

解析json格式直接.json就行

# 前后分离后,后端给的数据,都是json格式,

# 解析json格式

res = requests.get(
    'https://api.map.baidu.com/place/v2/search?ak=6E823f587c95f0148c19993539b99295&region=%E4%B8%8A%E6%B5%B7&query=%E8%82%AF%E5%BE%B7%E5%9F%BA&output=json')
print(res.text)
print(type(res.text))
print(res.json()['results'][0]['name'])
print(type(res.json()))

标签:01,请求,get,res,爬虫,学习,cookie,print,requests
From: https://www.cnblogs.com/zzjjpp/p/16918365.html

相关文章