爬虫知识--02

news2024/10/7 2:23:19

免费代理池搭建

# 代理有免费和收费代理
# 代理有http代理和https代理
# 匿名度:
        高匿:隐藏访问者ip
        透明:服务端能拿到访问者ip
        作为后端,如何拿到使用代理人的ip
        请求头中:x-forword-for
        如一个 HTTP 请求到达服务器之前,经过了三个代理 Proxy1、Proxy2、Proxy3,IP 分别为 IP1、IP2、IP3,用户真实IP为IP0,那么按照XFF标准,服务端最终会收到以下信息:
                X-Forwarded-For: IP0, IP1, IP2
                如果拿IP3,remote-addr中        
# 搭建免费代理池:

        https://github.com/jhao104/proxy_pool
    使用python,爬取免费的代理,解析出ip和端口,地区,存到库中
    使用flask,搭建了一个web服务,只要向 /get 发送一个请求,他就随机返回一个代理ip
# 步骤:
        1、把项目下载下来
        2、安装依赖,虚拟环境     pip install -r requirements.txt
        3、修改配置文件
                            DB_CONN = 'redis://127.0.0.1:6379/2'
        4、启动爬虫:python proxyPool.py schedule
        5、启动web服务:python proxyPool.py server

6、以后访问:http://127.0.0.1:5010/get/   可以拿到随机的免费ip

7、使用代码:

import requests

res = requests.get('http://192.168.1.51:5010/get/?type=https').json()
print(res['proxy'])

# 访问某个代理
res1=requests.get('https://www.baidu.com',proxies={'http':res['proxy']})
print(res1)

# 项目下载:

代理池使用

# 使用django写个项目,只要一访问,就返回访问者ip

# 编写步骤:
1、编写django项目,写一个视图函数:

def index(request):
    ip=request.META.get('REMOTE_ADDR')
    return HttpResponse('您的ip 是:%s'%ip)

2、配置路由:

from app01.views import index
urlpatterns = [
     path('', index),
]

3、删除settings.py 中的数据库配置

4、把代码上传到服务端,运行djagno项目
        python3.8 manage.py runserver 0.0.0.0:8080

5、本地测试:

import requests
res=requests.get('http://127.0.0.1:5010/get/?type=http').json()
print(res['proxy'])
res1=requests.get('http://47.113.229.151:8080/',proxies={'http':res['proxy']})
print(res1.text)

爬取某视频网站

 注意:
 1 发送ajax请求,获取真正视频地址
 2 发送ajax请求时,必须携带referer
 3 返回的视频地址,需要处理后才能播放

import requests
import re

res = requests.get('https://www.pearvideo.com/category_loading.jsp?reqType=5&categoryId=1&start=0')
# print(res.text)
# 解析出所有视频地址---》re解析
video_list = re.findall('<a href="(.*?)" class="vervideo-lilink actplay">', res.text)
for video in video_list:
    real_url = 'https://www.pearvideo.com/' + video
    video_id = video.split('_')[-1]
    # 必须携带referer,referer是视频详情地址
    # contId  是视频id号
    header={
        'Referer':real_url
    }
    res = requests.get('https://www.pearvideo.com/videoStatus.jsp?contId=%s&mrd=0.05520583472057039'%video_id,headers=header)
    real_mp4_url=res.json()['videoInfo']['videos']['srcUrl']
    mp4 = real_mp4_url.replace(real_mp4_url.split('/')[-1].split('-')[0], 'cont-%s' % video_id)
    print('能播放的视频地址:',mp4)

    # 把视频下载到本地
    res=requests.get(mp4)
    with open('./video/%s.mp4'%video_id,'wb') as f:
        for line in res.iter_content():
            f.write(line)

爬取新闻

# 解析库:汽车之家
# bs4 解析库  pip3 install beautifulsoup4

          lxml:  pip3 install lxml

# 爬取所有数据:

import requests
from bs4 import BeautifulSoup

res = requests.get('https://www.autohome.com.cn/news/1/#liststart')
print(res.text)

# 取出文章详情:

import requests
from bs4 import BeautifulSoup

res = requests.get('https://www.autohome.com.cn/news/1/#liststart')
print(res.text)

soup = BeautifulSoup(res.text, 'html.parser')  # 解析库
ul_list = soup.find_all(name='ul', class_='article')  # 找到所有 类名是article 的ul标签
for ul in ul_list:  # 查找ul标签下的li标签
    li_list = ul.find_all(name='li')
    for li in li_list:
        h3 = li.find(name='h3')  # 查找li标签下的所有h3标题
        if h3:
            title = h3.text  # 拿出h3标签的文本内容
            content = li.find('p').text  # 拿出li标签下的第一个p标签的文本内容
            url = 'https:' + li.find(name='a').attrs['href']  # .attrs 拿到标签属性
            img = li.find('img')['src']  # 拿出img标签的属性src,可以直接取
            print('''
            文章标题:%s
            文章摘要:%s
            文章url:%s
            文章图片:%s
            ''' % (title, content, url, img))

bs4介绍和遍历文档树

# bs4的概念:是解析 xml/html 格式字符串的解析库
        不但可以解析(爬虫),还可以修改

# 解析库:

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_xx' xx='zz'>lqz <b>The Dormouse's story <span>彭于晏</span></b>  xx</p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""
# soup=BeautifulSoup(html_doc,'html.parser')
soup = BeautifulSoup(html_doc, 'lxml')  # pip3 install lxml

1、文档容错能力:
        res=soup.prettify()
        print(res)

2、遍历文档树: 文档树:html开头 ------html结尾,中间包含了很多标签
        print(soup.html.head.title)

3、通过 . 找到p标签  只能找到最先找到的第一个
        print(soup.html.body.p)
        print(soup.p)

4、获取标签的名称
        p = soup.html.body.p
        print(p.name)

5、获取标签的属性
        p = soup.html.body.p
        print(p.attrs.get('class'))         # class 特殊,可能有多个,所以放在列表汇总
        print(soup.a.attrs.get('href'))
        print(soup.a['href'])

6、获取标签的文本内容

标签对象.text            # 拿标签子子孙孙
标签对象.string         # 该标签有且只有自己有文本内容才能拿出来
标签对象.strings       # 拿子子孙孙,都放在生成器中
print(soup.html.body.p.b.text)
print(soup.html.body.p.text)
print(soup.html.body.p.string) # 不能有子 孙
print(soup.html.body.p.b.string) # 有且只有它自己

print(soup.html.body.p.strings) # generator 生成器---》把子子孙孙的文本内容都放在生成器中,跟text很像
print(list(soup.html.body.p.strings)) # generator 生成器---》把子子孙孙的文本内容都放在生成器中,跟text很像

7、嵌套选的:
        soup.html.body

# -----了解-----------:

# 子节点、子孙节点
print(soup.p.contents) # p下所有子节点,只拿直接子节点
print(soup.p.children) # 直接子节点 得到一个迭代器,包含p下所有子节点
for i,child in enumerate(soup.p.children):
    print(i,child)

print(soup.p.descendants) #获取子孙节点,p下所有的标签都会选择出来  generator
for i,child in enumerate(soup.p.descendants):
    print(i,child)

# 父节点、祖先节点
print(soup.a.parent) #获取a标签的父节点
print(list(soup.a.parents)) #找到a标签所有的祖先节点,父亲的父亲,父亲的父亲的父亲...

# 兄弟节点
print(soup.a.next_sibling) #下一个兄弟
print(soup.a.previous_sibling) #上一个兄弟

print(list(soup.a.next_siblings)) #下面的兄弟们=>生成器对象
print(soup.a.previous_siblings) #上面的兄弟们=>生成器对象

搜索文档树

# 解析库:

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my_p" class="title"><b id="bbb" class="boldest">The Dormouse's story</b>
</p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(html_doc, 'lxml')

# 五种过滤器: 字符串、正则表达式、列表、True、方法
1、字符串(和):

res=soup.find(id='my_p')
res=soup.find(class_='boldest')
res=soup.find(href='http://example.com/elsie')
res=soup.find(name='a',href='http://example.com/elsie',id='link1',class_='sister') # 多个是and条件
# 可以写成
# res=soup.find(attrs={'href':'http://example.com/elsie','id':'link1','class':'sister'})
# print(res)

2、正则表达式:

import re
res=soup.find_all(href=re.compile('^http'))
res=soup.find_all(name=re.compile('^b'))
res=soup.find_all(name=re.compile('^b'))
print(res)

3、列表(或):

res=soup.find_all(name=['body','b','a'])
res=soup.find_all(class_=['sister','boldest'])
print(res)

4、布尔:

res=soup.find_all(id=True)
res=soup.find_all(name='img',src=True)
print(res)

5、方法:

def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')
print(soup.find_all(has_class_but_no_id))

6、搜索文档树可以结合遍历文档树一起用

res=soup.html.body.find_all('p')
res=soup.find_all('p')
print(res)

7、find 和find_all的区别:find 就是find_all,只要第一个

8、recursive=True   limit=1

res=soup.find_all(name='p',limit=2) # 限制条数
res=soup.html.body.find_all(name='p',recursive=False) # 是否递归查找
print(res)

css选择器

# 解析库:

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my_p" class="title"><b id="bbb" class="boldest">The Dormouse's story</b>
</p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'lxml')

# css 选择器:

'''
.类名
#id
body
body a
# 终极大招:css选择器,复制
'''
res=soup.select('a.sister')
res=soup.select('p#my_p>b')
res=soup.select('p#my_p b')
print(res)


import requests
from bs4 import BeautifulSoup
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.get('https://www.zdaye.com/free/',headers=header)
# print(res.text)
soup=BeautifulSoup(res.text,'lxml')
res=soup.select('#ipc > tbody > tr:nth-child(2) > td.mtd')
print(res[0].text)

今日思维导图:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1460273.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Python爬虫】requests库get和post方法使用

requests库是一个常用于http请求的模块&#xff0c;性质是和urllib&#xff0c;urllib2是一样的&#xff0c;作用就是向指定目标网站的后台服务器发起请求&#xff0c;并接收服务器返回的响应内容。 1. 安装requests库 使用pip install requests安装 如果再使用pip安装python…

Fiddler工具 — 18.Fiddler抓包HTTPS请求(一)

1、Fiddler抓取HTTPS过程 第一步&#xff1a;Fiddler截获客户端发送给服务器的HTTPS请求&#xff0c;Fiddler伪装成客户端向服务器发送请求进行握手 。 第二步&#xff1a;服务器发回相应&#xff0c;Fiddler获取到服务器的CA证书&#xff0c; 用根证书&#xff08;这里的根证…

Android 浅色皮肤阴影开发

前言&#xff1a;项目中要进行浅色皮肤开发&#xff0c;然后要求要有阴影效果&#xff0c;下面是UI觉得可行的中立方案效果 尝试一、使用elevation添加阴影发现效果一般 尝试二、使用带阴影的UI切图后续发现成本太大&#xff0c;对后续多个皮肤适配要求太大 尝试三、使用elevat…

oppo手机如何录屏?解锁录屏新功能!

“最近换了一款oppo手机&#xff0c;感觉它的拍照功能真的很强大。但除此之外&#xff0c;我发现oppo还有许多隐藏功能&#xff0c;比如录屏。但我尝试了很久&#xff0c;都没找到录屏的开关在哪里。有没有哪位oppo用户知道怎么打开这个功能呢&#xff1f;” 随着科技的不断发…

【小样本命名实体识别】COPNER论文源码详解

COPNER: Contrastive Learning with Prompt Guiding for Few-shot Named Entity Recognition 原文与代码链接&#xff1a; https://github.com/AndrewHYC/COPNER 一、项目结构 二、代码分析 1.定义参数 配置训练环境 parser.add_argument(--gpu, default0,helpthe gpu num…

Spring最新核心高频面试题(持续更新)

1 什么是Spring框架 Spring框架是一个开源的Java应用程序开发框架&#xff0c;它提供了很多工具和功能&#xff0c;可以帮助开发者更快地构建企业级应用程序。通过使用Spring框架&#xff0c;开发者可以更加轻松地开发Java应用程序&#xff0c;并且可以更加灵活地组织和管理应…

js设计模式:原型模式

作用: 使用js特有的原型链机制,可以通过Object.create方法创建新对象,将一个对象作为另外一个对象的原型 也可以通过修改原型链上的属性,影响新对象的行为 可以更方便的创建一些对象 示例: let obj {getName: function(){return this.name},getAge:function(){return this…

Python学习-用Python设计第一个游戏

三、用Python设计第一个游戏 1、新建文件 使用IDLE的编辑器模式&#xff0c;新建一个文件&#xff0c;点击File—>New File 2、将下面的游戏代码敲入进去 """用Python设计第一个游戏"""temp input("不妨猜一下小甲鱼现在心里想的是…

Excel练习:双层图表

Excel练习&#xff1a;双层图表 学习视频Excel制作双层图表&#xff0c;很多人都不会&#xff0c;其实只需1步操作就够了&#xff01;_哔哩哔哩_bilibili ​​ 通过调整两个图形的显示范围实现 增加折现图的负数显示范围&#xff0c;使折现图仅出现在整体图形的上方增加柱形…

ABAQUS应用04——集中质量的添加方法

文章目录 0. 背景1. 集中质量的编辑2. 约束的设置3. 总结 0. 背景 混塔ABAQUS模型中&#xff0c;机头、法兰等集中质量的设置是模型建立过程中的一部分&#xff0c;需要研究集中质量的添加。 1. 集中质量的编辑 集中质量本身的编辑没什么难度&#xff0c;我已经用Python代码…

快速上手Spring Boot整合,开发出优雅可靠的Web应用!

SpringBoot 1&#xff0c;SpringBoot简介1.1 SpringBoot快速入门1.1.1 开发步骤1.1.1.1 创建新模块1.1.1.2 创建 Controller1.1.1.3 启动服务器1.1.1.4 进行测试 1.1.2 对比1.1.3 官网构建工程1.1.3.1 进入SpringBoot官网1.1.3.2 选择依赖1.1.3.3 生成工程 1.1.4 SpringBoot工程…

7款自媒体写作神器:让内容创作更高效! #经验分享#人工智能#媒体

这些宝藏AI 写作神器&#xff0c;我不允许你还不知道~国内外免费付费都有&#xff0c;还有AI写作小程序分享&#xff0c;大幅度提高写文章、写报告的效率&#xff0c;快来一起试试吧&#xff01; 1.飞鸟写作 这是一个微信公众号 面向专业写作领域的ai写作工具&#xff0c;写作…

Qt的跨平台开发

自从最初发布以来&#xff0c;Qt就以其跨平台的能力而闻名——这是创建这个框架背后的主要愿景。您可以在自己喜欢的桌面平台(如Windows、Linux和mac OS)上使用Qt Creator&#xff0c;并使用相同的代码库或稍加修改&#xff0c;创建流畅、现代、触摸友好的图形用户界面(GUI)和桌…

Maxwell安装部署

1 Maxwell输出格式 database&#xff1a;变更数据所属的数据库table&#xff1a;变更数据所属的表type&#xff1a;数据变更类型ts&#xff1a;数据变更发生的时间xid&#xff1a;事务idcommit&#xff1a;事务提交标志&#xff0c;可用于重新组装事务data&#xff1a;对于inse…

Mysql 两个日期相减得到指定的格式数据

首先避坑&#xff1a; Mysql 中两个日期直接相减&#xff0c;若在同一天则得到的是秒&#xff0c;否则相减得到的并不是秒&#xff0c;一定要注意。 函数 TIMESTAMPDIFF(unit,begin,end); 函数返回 begin - end 的结果。 其中 begin 和 end 是 DATE 或 DATETIME 表达式。 …

Lightfm学习记录

推荐参考资料 官方文档仓库地址论文地址LightFM推荐系统框架学习笔记LightFM推荐模型库(利于入门)how-i-would-explain-building-lightfm-hybrid-recommenders-to-a-5-year-old(用处不大)协同推荐 lightfm 根据用户已读诗词推荐(可能有用)Recommendation System in Python: L…

【深度学习:人体姿态估计】计算机视觉人体姿态估计完整指南

【深度学习&#xff1a;人体姿态估计】计算机视觉人体姿态估计完整指南 什么是人体姿态估计&#xff1f;2D 人体姿态估计2D 人体姿态估计示例2D 与 3D 人体姿态估计人体姿态估计如何工作&#xff1f; 机器学习中人类姿态估计的挑战用于人体姿态估计的流行机器学习模型#1: OmniP…

线阵相机之帧超时

1 帧超时的效果 在帧超时时间内相机若未采集完一张图像所需的行数&#xff0c;则相机会直接完成这张图像的采集&#xff0c;并自动将缺失行数补黑出图&#xff0c;机制有以下几种选择&#xff1a; 1. 丢弃整张补黑的图像 2. 保留补黑部分出图 3.丢弃补黑部分出图

大数据分析/开发就业班新年钜惠活动来啦

2月26日-3月20日 开年钜惠活动 大数据分析/开发就业班即将开班 免费试学一周&#xff0c;额满即止

【sgCreateTableData】自定义小工具:敏捷开发→自动化生成表格数据数组[基于el-table]

源码 <template><!-- 前往https://blog.csdn.net/qq_37860634/article/details/136141769 查看使用说明 --><div :class"$options.name"><div class"sg-head">表格数据生成工具</div><div class"sg-container&quo…