一、爬虫介绍

# 爬虫介绍:
	网络爬虫(webcrawler)又称为网络蜘蛛(webspider)或网络机器人(webrobot),另外一些不常使用的名字还有蚂蚁、自动索引、模拟程序或蠕虫,同时它也是“物联网”概念的核心之一。网络爬虫本质上是一段计算机程序或脚本,其按照一定的逻辑和算法规则自动地抓取和下载万维网的网页,是搜索引擎的一个重要组成部分。

# 本质原理:
	现在所有的软件原理:大部分都是基于http请求发送和获取数据
    	pc端的网页
        移动端app
    爬虫就是模拟发送http请求,从别人的服务端获取数据
    如何绕过反扒:不同程序反扒措施不一样,比较复杂
    
    
# 爬虫原理
	发送http请求【requests,selenium】----》第三方服务端----》服务端响应的数据解析出想要的数据【selenium,bs4】---》入库(文件,excel,mysql,redis,mongodb。。)
    scrapy:专业的爬虫框架
    
    
# 爬虫是否合法
	爬虫协议:每个网站根路径下都有robots.txt,这个文件规定了,该网站哪些内容可以爬取,哪些不能爬取

二、request模块介绍

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

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

# 安装:pip3 install requests

# 各种请求方式:常用的就是requests.get()和requests.post()
>>> import requests
>>> r = requests.get('https://api.github.com/events')
>>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})
>>> r = requests.put('http://httpbin.org/put', data = {'key':'value'})
>>> r = requests.delete('http://httpbin.org/delete')
>>> r = requests.head('http://httpbin.org/get')
>>> r = requests.options('http://httpbin.org/get')

# 建议在正式学习requests前,先熟悉下HTTP协议

三、基于GET请求

3.1 基本get请求

# 前提:安装request模块
	pip install request
# 基本使用:
    import requests

    info = requests.get('https://baike.baidu.com/item/%E4%B8%AD%E5%9B%BD%E5%8E%86%E5%8F%B2/152769')

    print(info.text)  # 获取http响应体中的文本内容

3.2 get请求携带params

import request

# 地址栏中拼接

info = requests.get('https://www.baidu.com/s?wd=%E5%8E%86%E5%8F%B2')

print(info.text)


# 使用params携带参数

info = requests.get('https://www.baidu.com/s', params={
    'wd': '历史',
    'country': 'china'
})
print(info.text)

# https://www.baidu.com/s?wd=历史&country=China


# url编码和解码

from urllib import parse

info = parse.quote('历史')           # url编码
print(info)     # %E5%8E%86%E5%8F%B2

info = parse.unquote('%E5%8E%86%E5%8F%B2')     # url解码
print(info)     # 历史

3.3 get请求携带headers

# 请求头中带数据,有些网站采取了反爬措施,我们可以绕过反爬去获取数据,比如在请求头中带参数,即客户端类型

import requests

header = {
    # User-Agent就是客户端类型,key-value的形式,后面的参数中显示了当前客户端的系统类型,以及使用的浏览器版本
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
}

info = requests.get('https://dig.chouti.com/', headers=header)  # 这个网站做了反爬,请求响应头中的文本数据无法获取,我们在请求头中携带参数就可以获取
print(info.text)


# 除了User-Agent,还有referer,它记录了上次访问的地址  Referer: https://www.lagou.com/gongsi/

# 比如模拟用户登录,当我们向下面这个地址发送请求时,正常应该是在登录的页面上去完成登录,如果我们没有携带referer,那么它就认为你是恶意的请求,拒绝登录

# https://passport.lagou.com/login/login.html?service=https%3a%2f%2fwww.lagou.com%2f

# referer还可以用于图片防盗链机制,如果referer指向地址的不是我们自己的域名,那就不允许你下载图片

3.4 get请求携带cookie

# cookie,认证后的cookie,就相当于是登录了

# 方式一:直接放在请求头中

import requests

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

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

四、基于POST请求

4.1 基本POST请求

# 发送POST请求

import requests

data = {
    'username': '1652814964@qq.com',
    'password': '******',
    'captcha': 'cccc',
    'remember': '1',
    'ref': 'http://www.aa7a.cn/',
    'act': 'act_login'
}
info = requests.post('http://www.aa7a.cn/user.php', data=data)
print(info.text)
print(info.cookies)  # 响应头中的cookie,如果正常登录,这个cookie就是登录后的cookie  RequestsCookieJar:当成字典


# 携带cookie访问首页

info1 = requests.get('http://www.aa7a.cn/', cookies=info.cookies)   # 不携带cookie就是False
print('1652814964@qq.com' in info1.text)   # True

4.2 post请求携带参数

# POST请求携带参数,data={}  json={}

# data={}是使用默认编码格式:urlencoded

# json={}是使用编码格式: json

import request

info = requests.post('http://www.aa7a.cn/user.php', json={})
print(info.text)

4.3 request.session使用

# request.session的使用,可以当做request使用,但是它可以自动维护cookie

import requests

session = requests.session()
data = {
    'username': '1652814964@qq.com',
    'password': '*******',
    'captcha': 'cccc',
    'remember': '1',
    'ref': 'http://www.aa7a.cn/',
    'act': 'act_login'
}
info = session.post('http://www.aa7a.cn/user.php', data=data)

info1 = session.get('http://www.aa7a.cn/')
print('1652814964@qq.com' in info1.text)   # True

五、响应Response

5.1 Response属性

import requests

header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 0.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': 'jason', 'age': 18},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

image = requests.get('http://www.aa7a.cn/data/afficheimg/20220913pmsadf.png')
with open('图片.png', 'wb') as f:
    f.write(image.content)

# 如果获取的视频数据过大,可能会出现问题,所以对于视频的数据的获取,我们可以分开去拿

MP4 = requests.get(
    'https://vd3.bdstatic.com/mda-mk21ctb1n2ke6m6m/sc/cae_h264/1635901956459502309/mda-mk21ctb1n2ke6m6m.mp4')
with open('视频.mp4', 'wb') as f:
    for line in MP4.iter_content():  # 迭代的一行一行取数据
        f.write(line)

七、解析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()))

原文地址:http://www.cnblogs.com/dy12138/p/16919729.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性