首页 > 其他分享 >爬虫基础

爬虫基础

时间:2022-11-23 20:47:14浏览次数:29  
标签:请求 get res 基础 爬虫 print requests

爬虫介绍

1.爬虫
1.1什么是爬虫
通过编写程序,模拟浏览器上网,然后让其去互联网上抓取数据的过程
1.2现在所有的软件原理:大部分都是基于http请求发送和获取数据的
-pc端的网页
-移动端app
-模拟发送http请求,从别人的服务端获取数据
-绕过反扒:不同程序反扒措施不一样,比较复杂

2.爬虫的合法性
2.1善意爬虫:
-不破坏被爬取的网站的资源,也就是正常的访问,一般频率都不高,不窃取用户隐私
2.2恶意爬虫:
-爬虫干扰了被访问网址的正常运营
-爬虫抓取了受到法律保护的特定类型的数据或信息
2.3如何避免进局子
-经常优化自己的程序,避免干扰哦被访问网址的正常运行
-爬取到涉及到用户隐私或商业机密等敏感内容时,要及时停止爬取或传播
2.4robots.txt协议
-规定了网站中哪些数据可以被爬取,哪些数据不可以被爬取
-robots.txt协议是君子协议,没有强制性
-网站首页的网址后加robots.txt,可以查询该网站的协议

3.爬虫的基本流程
-发送http请求【requests,selenium】----》第三方服务端----》服务端响应的数据解析出想要的数据【selenium,bs4】---》入库(文件,excel,mysql,redis,mongodb。。)
-scrapy:专业的爬虫框架

requests模块发送get请求

1.模拟发送http请求的模块:requests 不仅仅做爬虫用它,调用第三方接口,也是要用它的
1.1下载模块(本质是封装了内置模块urlib3)
pip3 install requests

2.使用
import requests
res=requests.get('https://www.cnblogs.com/liuqingzheng/p/16005866.html')
print(res.text)  # http响应体的文本内容

get请求携带参数

1.get请求携带参数
import requests

url = 'https://www.baidu.com/s?ie=UTF-8'
params = {
    'wb': '周杰伦'
}
res = requests.get(url, params=params)
# 路径:https://www.baidu.com/s?ie=UTF-8&wd=周杰伦
# 解析
print(res.text)
# 关掉爬虫请求
res.close()

2.url编码解码
# 周杰伦被url编码后:%E5%91%A8%E6%9D%B0%E4%BC%A6
from urllib import parse
res = parse.unquote('%E5%91%A8%E6%9D%B0%E4%BC%A6')
print(res)  # 周杰伦

携带请求头

1.有些网站通过某些请求头来做反爬,在请求头中带数据,才能爬取某个网站
1.1User-Agent:客户端类型:有浏览器,手机端浏览器,爬虫类型,程序,scrapy。。一般伪造成浏览器
1.2referer:上次访问的地址
1.3cookie: 认证后的cookie,就相当于登录了

1.2在headers加入需要的请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
}
# 将参数设置为动态的
kw = input('enter a word:')
# 将url携带的参数封装到字典中,将动态关键词设置为字典的v值
url = f'https://www.sogou.com/web?query={kw}'
# 发起get请求,对指定的url发起的请求定义的url是携带参数的,就是我们处理后的params
# 将请求头信息的User-Agent指定为headers字典的身份标识
res = requests.get(url=url, headers=headers)
# 获取响应数据
print(res.text)
# 关掉爬虫请求
response.close()

请求头携带cookie

1.直接在请求头中携带
import requests

data = {
    'linkId': '36996038'
}
header = {
    # 客户端类型
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.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)
# 关掉爬虫请求
res.close()

发送post请求

1.post请求
import requests

data = {
    'username': '[email protected]',
    'password': 'lqz123',
    '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)
res2 = requests.get('http://www.aa7a.cn/', cookies=res.cookies)
print('[email protected]' in res2.text)  # True
# 关掉爬虫请求
res.close()
res2.close()

2.request.session
import requests

session = requests.session()
data = {
    'username': '[email protected]',
    'password': 'lqz123',
    '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/')  # 登录过了就已经携带了cookies
print('[email protected]' in res2.text)  # True
# 关掉爬虫请求
res.close()
res2.close()

响应Response

import requests

header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.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)  # 页面编码

获取二进制数据

1.下载图片
import requests

res = requests.get(    'https://img1.baidu.com/it/u=1280456730,3064908281&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=888')
with open('a1.jpg', 'wb') as f:
    f.write(res.content)

2.下载视频
import requests

res = requests.get(
    'https://video.pearvideo.com/mp4/adshort/20210122/cont-1717669-15584915_adpkg-ad_hd.mp4')
with open('b1.mp4', 'wb') as f:
    for line in res.iter_content():
        f.write(line)

解析解析json

-前后分离,后端给的数据,都是json格式
import requests

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(res.json()['results'][0]['name'])
# 关掉爬虫请求
res.close()

标签:请求,get,res,基础,爬虫,print,requests
From: https://www.cnblogs.com/riuqi/p/16919722.html

相关文章