爬虫-(1)

内容概览

  • 爬虫介绍
  • requests模块发送get请求
  • get请求携带参数
  • 携带请求头
  • 携带cookie
  • 发送post请求
  • 响应Response
  • 获取二进制数据
  • 解析json

爬虫介绍

# 爬虫:spider,网络蜘蛛

# 本质原理:
	-现在所有的软件原理:大部分都是基于http请求发送和获取数据的
    	-pc端的网页
        -移动端app
    -模拟发送http请求,从别人的服务端获取数据
    -绕过反扒:不同程序反扒措施不一样,比较复杂
    
    
# 爬虫原理
	-发送http请求【requests,selenium】----》第三方服务端----》服务端响应的数据解析出想要的数据【selenium,bs4】---》入库(文件,excel,mysql,redis,mongodb。。)
    -scrapy:专业的爬虫框架
    
    
# 爬虫是否合法
	-爬虫协议:每个网站根路径下都有robots.txt,这个文件规定了,该网站,哪些可以爬取,哪些不能爬
    
    
    
# 百度
	-百度搜索框中输入搜索内容,回车,返回的数据,是百度数据库中的数据
    -百度一刻不停的在互联网中爬取各个页面,链接地址--》爬完存到自己的数据库
    -当你点击,跳转到真正的地址上去了
    -核心:搜索,海量数据中搜索出想要的数据
    -seo:免费的搜索,排名靠前
    -sem:花钱买关键字

requests模块发送get请求

# 模拟发送http请求的模块:requests 不仅仅做爬虫用它,后期调用第三方接口,也是要用它的
# pip3 install requests	
	-本质是封装了内置模块urlib3

import requests

res = requests.get('https://www.csdn.net/')
print(res.text)  # http响应体的文本内容

get请求携带参数

import requests

#  发送get请求携带数据
#  1. 地址栏中拼接
res = requests.get('https://www.baidu.com/s?wd=%E7%BE%8E%E5%A5%B3')
print(res.text)  # 有反爬,返回的不是正常的数据

# 2. 使用params参数携带
res = requests.get('https://www.baidu.com/s', params={
    'wd': '美女',
})
print(res.text)

"""url编码和解码"""
# 美女被url编码后--》
# %E7%BE%8E%E5%A5%B3
from urllib import parse
res1 = parse.quote('美女')
print(res1)  # %E7%BE%8E%E5%A5%B3
res2 = parse.unquote('%E7%BE%8E%E5%A5%B3')
print(res2)  # 美女
 

携带请求头

"""
http 请求,有请求头,有的网站,通过某些请求头来做反爬
爬取某个网站,不能正常返回,模拟的不像---->请求头中需要夹带数据
网站做反爬,查看请求头中的客户端类型
User-Agent:客户端类型:有浏览器,手机端浏览器,爬虫类型,程序,scrapy。。一般伪造成浏览器
referer:上次访问的地址:Referer: https://www.lagou.com/gongsi/
	如果要登录,模拟向登录接口发请求,正常操作必须在登录页面上才能干这事,如果没有携带referer,它就认为你是恶意的,拒绝访问
cookie: 认证后的cookie,就相当于登录了
"""
import requests

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/')  # 被防火墙拦截
res = requests.get('https://dig.chouti.com/',headers=header)  # 正常返回数据
print(res.text)

携带cookie

import requests

# 请求中携带cookie
# 1. 直接带在请求头中
# 模拟点赞

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':'xxxxxxxx'
}
res = requests.post('https://dig.chouti.com/link/vote',data=data, headers=header)
print(res.text)

# 2. 通过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'})  # cookie中都是xx=xx的形式;以键值对的形式填入
print(res.text)

发送post请求

import requests

data = {  # 携带的数据
    'username': 'xxx@xx.com',
    'password': '****',
    'captcha': 'cccc',
    '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(RequestsCookieJar对象,可以当做字典)

# 携带cookie访问首页
# res2 = requests.get('http://www.aa7a.cn/')  # False
res2 = requests.get('http://www.aa7a.cn/', cookies=res.cookies)  # True
print('xxx@xx.com' in res2.text)

# post请求携带数据 data={} ,json={}   drf后端,打印 request.data
# data=字典是使用默认编码格式:urlencoded
# json=字典是使用json 编码格式
res1 = requests.post('http://127.0.0.1:8000/', data={'name': 'xxx'})
res2 = requests.post('http://127.0.0.1:8000/', json={'name': 'xxx'})
"""
drf:
    def test(request):
        res = request.body
        return HttpResponse(res)
"""
print(res1.text)  # name=xxx
print(res2.text)  # {"name": "xxx"}

# requests.session的使用:当成requests使用,但是可以自动维护cookie
session = requests.session()
data = {
    'username': 'xxx@xx.com',
    'password': '****',
    'captcha': 'cccc',
    '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('xxx@xx.com' in res2.text)  # True

响应Response

import requests

"""Response对象,有很多属性和方法"""
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': 'lqz', 'age': 19},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)  # 页面编码

获取二进制数据

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

res = requests.get(
    'https://upload.jianshu.io/admin_banners/web_images/5067/5c739c1fd87cbe1352a16f575d2df32a43bea438.jpg')
with open('图片.jpg', 'wb') as f:
    f.write(res.content)

"""如果数据较大,可以一段一段的写"""
res=requests.get('https://vd3.bdstatic.com/mda-mk21ctb1n2ke6m6m/sc/cae_h264/1635901956459502309/mda-mk21ctb1n2ke6m6m.mp4')
with open('视频.mp4', 'wb') as f:
    for line in res.iter_content():
        f.write(line)

解析json

import requests

"""前后端分离后,后端发送给前端的数据,都是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))  # <class 'str'>
print(res.json())
print(type(res.json()))  # <class 'dict'>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值