首页 > 其他分享 >爬虫——day01

爬虫——day01

时间:2024-02-19 15:37:21浏览次数:25  
标签:http res day01 爬虫 --- https print requests

爬虫介绍

爬虫是什么?
  -通过编程技术---》把互联网中的数据---》获取到---》数据清洗---》存到库中
python:request,selenium---》app,小程序,网站---》xpaht,lxml---》mysql,redis,文件,excel,mongodb
  -通过编程语言---》模拟发送http请求---》获取数据---》解析--》入库
  -爬取过程 解析过程 会遇到反扒
  -抓app,小程序---》抓包工具---》抓取手机发送的所有请求
    -charles
    -Fiddler

# 爬虫 有爬虫协议
  -协议
    -https://xxx/robots.txt
# 百度 是个大爬虫
  -百度/谷歌 搜索引擎---》启动了一个爬虫---》一刻不停的在互联网中爬取网站---》存到库中(es)
  -用户在百度输入框中---》输入搜索内容---》去百度的库中搜索--》返回给前端---》前端点击---》去了真正的地址

-seo 优化
  -不花钱---》搜索关键词的结果---》排的靠前
  -伪静态
-sem 优化
  -花钱买关键词

requests模块介绍和快速使用

requests:模拟发送http请求模块---》封装了urlib3[python内置的发送http请求的模块]
  -爬虫会用
  -后端---》向其他api接口发送请求
  -同步

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

requests发送get请求

requests可以模拟发送http请求,有的时候,网站会禁止---》禁止的原因是:模拟的不像,有的东西没带
# http请求:请求头中没带东西,没带cookie,客户端类型,referer。。。
  import requests
# 这个网站没有反扒
  res=requests.get('https://www.cnblogs.com/')
  print(res.text) # 响应体内容

携带get参数

import requests

# 1 url编码和解码  %E4%B8%8A%E6%B5%B7   上海

# res=requests.get('https://api.map.baidu.com/place/v2/search?ak=6E823f587c95f0148c19993539b99295&region=上海&query=肯德基&output=json')


# 2 携带get参数,第二种方式
params = {
    'ak': '6E823f587c95f0148c19993539b99295',
    'region': '上海',
    'query': '肯德基',
    'output': 'json',
}
res = requests.get('https://api.map.baidu.com/place/v2/search',params=params)

print(res.text)  # 响应体内容


### url 编码和解码

from urllib.parse import quote,unquote
# s='上海'  # %E4%B8%8A%E6%B5%B7
# print(quote(s))

print(unquote('%E4%B8%8A%E6%B5%B7'))

携带请求头

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
res = requests.get('https://dig.chouti.com/',headers=headers)
print(res.text)

发送post请求

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
    'Cookie': 'deviceId=web.eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqaWQiOiJiNjEzOGM2OS02ZWRlLTQ3MWItODI4Yy03YTg2ZTE3M2E3NjEiLCJleHBpcmUiOiIxNzEwOTAxNjM1MTMxIn0.JluPFMn3LLUGKeTFPyw7rVwR-BWLiG9V6Ss0RGDHjxw; Hm_lvt_03b2668f8e8699e91d479d62bc7630f1=1708309636; __snaker__id=miaeDoa9MzunPIo0; gdxidpyhxdE=lMhl43kDvnAOqQQcQs9vEoTiy8k90nSwfT3DkVSzGwu3uAQWI9jqa2GcIUvryeOY0kX6kfPuhJUAGrR6ql0iv%2F6mCzqh6DHE1%5CP%2BaIXeUQgLcfqlklCcq2V9CgWbvQRGeRaduwzkcPYwf6CXZiW9a87NxU%2BRlYq57Zq01j2gMK0BaX%2FK%3A1708310847499; token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqaWQiOiJjZHVfNTMyMDcwNzg0NjAiLCJleHBpcmUiOiIxNzEwOTAxOTY5NTM2In0.eseWTCMqp-yHa7rWgSvPhnWVhhQAgqGIvIgLGbvcBcc; Hm_lpvt_03b2668f8e8699e91d479d62bc7630f1=1708309982'
}
data = {
    'linkId': '41566118'
}
# 没有登录---》返回的数据不是咱们想要的
res = requests.post('https://dig.chouti.com/link/vote', headers=headers, data=data)
print(res.text)

携带cookie

import requests

'''
是否登录---》有个标志
 1 前后端混合项目---》登录信息-->放在cookie中了
 2 前后端分离项目---》登录信息--》后端规定的--》放在请求头的


'''
### 携带cookie的第一种方式:放在请求头中
# headers = {
#     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
#     'Cookie': 'deviceId=web.eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqaWQiOiJiNjEzOGM2OS02ZWRlLTQ3MWItODI4Yy03YTg2ZTE3M2E3NjEiLCJleHBpcmUiOiIxNzEwOTAxNjM1MTMxIn0.JluPFMn3LLUGKeTFPyw7rVwR-BWLiG9V6Ss0RGDHjxw; Hm_lvt_03b2668f8e8699e91d479d62bc7630f1=1708309636; __snaker__id=miaeDoa9MzunPIo0; gdxidpyhxdE=lMhl43kDvnAOqQQcQs9vEoTiy8k90nSwfT3DkVSzGwu3uAQWI9jqa2GcIUvryeOY0kX6kfPuhJUAGrR6ql0iv%2F6mCzqh6DHE1%5CP%2BaIXeUQgLcfqlklCcq2V9CgWbvQRGeRaduwzkcPYwf6CXZiW9a87NxU%2BRlYq57Zq01j2gMK0BaX%2FK%3A1708310847499; token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqaWQiOiJjZHVfNTMyMDcwNzg0NjAiLCJleHBpcmUiOiIxNzEwOTAxOTY5NTM2In0.eseWTCMqp-yHa7rWgSvPhnWVhhQAgqGIvIgLGbvcBcc; Hm_lpvt_03b2668f8e8699e91d479d62bc7630f1=1708309982'
# }
# data = {
#     'linkId': '41566118'
# }
# # 没有登录---》返回的数据不是咱们想要的
# res = requests.post('https://dig.chouti.com/link/vote', headers=headers, data=data)
# print(res.text)


### 携带cookie的第一种方式:放在cookie参数中---》cookie特殊--》后期用的频率很高
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
}
data = {
    'linkId': '41566118'
}
cookie = {
    'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqaWQiOiJjZHVfNTMyMDcwNzg0NjAiLCJleHBpcmUiOiIxNzEwOTAxOTY5NTM2In0.eseWTCMqp-yHa7rWgSvPhnWVhhQAgqGIvIgLGbvcBcc'
}

# 没有登录---》返回的数据不是咱们想要的
res = requests.post('https://dig.chouti.com/link/vote', headers=headers, data=data, cookies=cookie)
print(res.text)

 

post请求携带参数

import requests
# 方式一:data参数:urlencoded
# post请求:三种编码方式:json,urlencoded,form-data
# 咱们以data字典形式携带--->urlencoded编码---》最终它会被编码为---》name=lqz&age=19 -->放在请体中
# res=requests.post('地址',data={'name':'lqz','age':19})
res=requests.post('地址',data=b'name=lqz&age=19')

# 方式二:json编码:json
# 咱们以json字典形式携带--->json编码---》最终它会被编码为---》{'name':'lqz','age':19} -->放在请体中
res=requests.post('地址',json={'name':'lqz','age':19})

 

模拟登录

# 发送post请求---》一般登录接口---》post请求---》登录成功后---》能拿到:登录信息---》以后再发请求---》携带登录信息--》就是登录状态

# 可见即可爬



import requests

data = {
    'username': '[email protected]',
    'password': 'lqz123',
    'captcha': '3333',
    'remember': '1',
    'ref': ' http://www.aa7a.cn/',  # 登录成功,重定向到这个地址
    'act': 'act_login',
}
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
res = requests.post('http://www.aa7a.cn/user.php', headers=header, data=data)
print(res.text)
# 登录成功的cookie
cookies=res.cookies
print(cookies)


# 向首页发送请求--->登录状态
res=requests.get('http://www.aa7a.cn/',cookies=cookies)
print('[email protected]' in res.text)

session对象

# http 请求,每次都是一个新的---》cookie需要自己处理携带
# session可以自动处理cookie,不需要手动携带了




import requests

session=requests.session()
# 以后发送请求使用session

data = {
    'username': '[email protected]',
    'password': 'lqz1233',
    'captcha': '3333',
    'remember': '1',
    'ref': ' http://www.aa7a.cn/',  # 登录成功,重定向到这个地址
    'act': 'act_login',
}
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
res = session.post('http://www.aa7a.cn/user.php', headers=header, data=data)


# 向首页发送请求--->登录状态

res=session.get('http://www.aa7a.cn/')
print('[email protected]' in res.text)

响应对象

# response 对象---》http响应

### 使用requests模块
# 发送请求:request对象:请求头,请求参数,请求体---》本质就是http请求--》被包装成一个对象
# 响应回来:response对象:http响应--》cookie,响应头,响应体。。

### django框架
    -request:http请求
    -response:http响应
    
# requests模块的response对象中有哪些东西?
    
    
# 爬取图片--》图片防盗链---》referfer--》请求头中即可
import requests

# header = {
#     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
# }
# respone = requests.get('https://www.jianshu.com/',headers=header)
# # respone属性
# print(respone.text)  # 响应体---》字符串形式
# print('------------')
# print(respone.content)  # 响应体---》bytes格式
# print('------------')
# print(respone.status_code)  # 响应状态码
#
# print(respone.headers)  # 响应头
# print(respone.cookies)  # 响应的cookie
# print(respone.cookies.get_dict())  # cookiejar对象--->转成字典格式
# print(respone.cookies.items())  # cookie的value值
#
# print(respone.url)  # 请求地址
# print(respone.history)  # 访问历史---》重定向,才会有
#
# print(respone.encoding)  # 编码格式

# response.iter_content() # 图片,视频---》迭代着把数据保存到本地

# 如果下载图片,视频。。。

# 图片防盗链---》通过referer做的--》请求头中有个referer参数--》上次访问的地址
# res=requests.get('https://tupian.qqw21.com/article/UploadPic/2022-2/20222102371522350.jpg')
header={
    'Referer':'https://www.tupianzj.com/'
}
res=requests.get('https://img.lianzhixiu.com/uploads/allimg/180514/9-1P514153131.jpg',headers=header)
# print(res.content)
# with open('美女.jpg','wb') as f:
#     f.write(res.content)
with open('code.jpg','wb') as f:
    for line in res.iter_content(chunk_size=1024):
        f.write(line)

ssl 认证

# http  和 https
    -http:超文本传输协议
    -https:安全的超文本传输协议
    -https=http+ssl/tls
    -防止:篡改,截取。。。。
    -必须有证书:才能通信
    
    
   


import requests

header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
respone = requests.get('https://www.jianshu.com/',headers=header,verify=False)
# respone = requests.get('https://www.jianshu.com/',headers=header,cert=('/path/server.crt','/path/key'))
print(respone.text)

使用代理

# 正向代理---》反向代理


# 代理有免费和收费的
    -大神写了开源的免费代理---》原理:有些网站提供免费的代理--》爬虫技术---》爬取别人的免费代理--》验证过后---》自己用
    





import requests

res = requests.get('http://demo.spiderpy.cn/get/?type=https')
print(res.json())
print(res.json()['proxy'])

# 112.30.155.83:12792
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
# respone = requests.get('https://www.jianshu.com/', headers=header, proxies={'https': res.json()['proxy']})
respone = requests.get('https://www.jianshu.com/', headers=header)
print(respone.text)

超时设置,异常处理,上传文件

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

# 异常处理
import requests
from requests.exceptions import * #可以查看requests.exceptions获取异常类型

try:
    r=requests.get('http://www.baidu.com',timeout=0.00001)
except ReadTimeout:
    print('===:')
# except ConnectionError: #网络不通
#     print('-----')
# except Timeout:
#     print('aaaaa')

except RequestException:
    print('Error')
    
    
    
    
# 上传文件

import requests
files={'file':open('a.jpg','rb')}
respone=requests.post('http://httpbin.org/post',files=files)
print(respone.status_code)

 

补充:  正向代理与反向代理

正向代理需要配置代理服务器,而反向代理不需要做任何设置

 

标签:http,res,day01,爬虫,---,https,print,requests
From: https://www.cnblogs.com/wzh366/p/18021205

相关文章

  • 【60行代码解决】2024年最新版python爬虫有道翻译js逆向
    一、表单参数sign加密sign:c0f36866a9c650144ed5bac4eba532a7这种32位一般是MD5加密1.搜索sign:2.点击去分别在每个**sign:某某某**处打上断点结果在这个断点断住了3.原代码constu="fanyideskweb",d="webfanyi"functionj(e){returnc.a.createHash......
  • 第 8章 Python 爬虫框架 Scrapy(下)
    第8章Python爬虫框架Scrapy(下)8.1Scrapy对接Selenium有一种反爬虫策略就是通过JS动态加载数据,应对这种策略的两种方法如下:分析Ajax请求,找出请求接口的相关规则,直接去请求接口获取数据。使用Selenium模拟浏览器渲染后抓取页面内容。8.1.1如何对接单独使用Sc......
  • 爬虫案例
    多进程和多线程爬虫案例importos.pathimporttimefrommultiprocessingimportProcessfromthreadingimportThreadimportrequestsfromlxmlimportetreefromfake_useragentimportUserAgentclassBaseSpider(object):def__init__(self):self.url......
  • day01_运维介绍与虚机安装
    上课须知1.上课的软件笔记软件typora记录markdown语法的文本编辑器通讯录于超1110-110101教你如何搭建游戏私服看看运维的操作。。网页游戏browser/server浏览器/服务器www.4399.comwww.taobao.com,服务端更新了,www.jd.com1.服务端,有一个企业,部署......
  • 爬虫_060_urllib post请求百度翻译的详细翻译
    目录百度翻译详细翻译接口关于复制的小技巧复制浏览器全部的requestheader代码百度翻译详细翻译接口这个接口,是我上一次用的接口,MD。关于复制的小技巧这个接口的参数数据就比较多了,我们都需要构建到data对象当中。这里可以第一步,先复制数据,然后粘贴到sublime当中。第二步......
  • 爬虫_059_urllib post请求百度翻译
    目录分析百度翻译找接口编写代码需要注意的点修改代码返回数据解析最后的说明分析百度翻译找接口编写代码importurllib.requestimporturllib.parseheaders={'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)......
  • 爬虫_058_urllib get请求的urlencode方法
    目录urllib.parse.urlencode()quote方法使用的不是很经常的。因为quote的作用是将汉字转为百分号编码后的ASCII字符串。如果你的路径当中只有一个参数,你这样使用quote拼接一下url,这是没有问题的。如果你的路径当中有多个参数,并且参数都是中文的,你还使用quote,就TMD懵逼了。......
  • 爬虫_057_urllib get请求的quote方法
    目录引子编码集的演变需求知识点重新测试get请求方式的quote方法引子将百度搜索周杰伦的地址栏地址,复制到pycharm当中变成下面的样子:https://www.baidu.com/s?wd=%E5%91%A8%E6%9D%B0%E4%BC%A6编码集的演变ASCII编码:一个字符一个字节中国:GB2312日本:Shift_JIS韩国:Euc-k......
  • 爬虫_056_urllib请求对象的定制
    目录url组成第一个反爬-UA校验制造一个UA请求对象的定制url组成协议httphttps主机www.baidu.com端口号http80https443mysql3306oracle1521redis6379mongodb27017路径参数?号锚点#号第一个反爬-UA校验制造一个UA从浏览器......
  • 爬虫_055_urllib下载
    目录下载网页下载图片下载视频总结下载网页下载图片下载视频总结真的,没有什么含金量,就是找到资源的地址,然后使用urllib.request.urlretrieve()就可以了。......