爬虫知识--02

免费代理池搭建

# 代理有免费和收费代理
# 代理有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 requestsres = 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 reres = 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/' + videovideo_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 BeautifulSoupres = requests.get('https://www.autohome.com.cn/news/1/#liststart')
print(res.text)

# 取出文章详情:

import requests
from bs4 import BeautifulSoupres = 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 BeautifulSouphtml_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 BeautifulSoupsoup = 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.mzph.cn/news/692632.shtml

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

相关文章

day3 2/20

1> 使用多进程完成两个文件的拷贝&#xff0c;父进程拷贝前一半&#xff0c;子进程拷贝后一半&#xff0c;父进程回收子进程的资源 #include<myhead.h> int main(int argc, const char *argv[]) {int fd1-1,fd2-1;if((fd1open("./ggb.bmp",O_RDONLY,0664))…

PropertyEditorRegistry与PropertyAccessor的学习

PropertyEditorRegister 简介 PropertyEditorRegistry 是 Spring 框架中的一个接口&#xff0c;它提供了注册和管理 PropertyEditor 的功能。PropertyEditor 是 Java Bean 规范的一部分&#xff0c;用于在不同类型的属性值和字符串之间进行转换。 PropertyEditorRegistry 接…

Go语言中的流程控制

「万事开头难&#xff0c;视频号500粉直播需要你的助力&#xff01;你的支持是我前进的动力&#xff01;」 1、Golang 中的流程控制 流程控制是每种编程语言控制逻辑走向和执行次序的重要部分&#xff0c;流程控制可以说是一门语言的“经脉”。Go 语言中最常用的流程控制有 if …

题目 1201: 回文数(一)

题目描述: 若一个数&#xff08;首位不为0&#xff09;从左到右读与从右到左读都是一样&#xff0c;这个数就叫做回文数&#xff0c;例如12521就是一个回文数。 给定一个正整数&#xff0c;把它的每一个位上的数字倒过来排列组成一个新数&#xff0c;然后与原数相加&#xff0…

【案例研习笔记】KodeRover_云时代 DevOps 建设

轻度量、轻流程、重开发者体验生产力工具建设要大于管理工具建设贴合自己业务&#xff0c;不要去求大求全

Ceph入门到精通-更换osd、扩容osd

1. 更换故障盘 1. 1 查看故障盘osd id ceph osd tree1.2 销毁osd ceph osd destroy 60 --yes-i-really-mean-it#ceph osd purge 60 --yes-i-really-mean-it #destroy可以保留osd id&#xff1b;purge不保留osd id1.3 更换故障硬盘 1.4 查看新硬盘盘符 lsblk1.5 擦除新硬盘…

如何使用快手item_search API

要使用快手&#xff08;Kuaishou&#xff09;的 item_search API&#xff0c;你首先需要确保你有访问该API的权限&#xff0c;这通常意味着你需要有一个有效的API密钥&#xff08;API Key&#xff09;和/或访问令牌&#xff08;Access Token&#xff09;。快手API的具体实现细节…

十六、包装类

文章目录 包装类2.1 基本用法2.2 共同点2.3 剖析Character 包装类 本文为书籍《Java编程的逻辑》1和《剑指Java&#xff1a;核心原理与应用实践》2阅读笔记 Java有 8 8 8种基本类型&#xff0c;每种基本类型都有一个对应的包装类。包装类是什么呢&#xff1f;它是一个类&…

SpirngBoot整合Redis解决缓存穿透、缓存击穿、缓存雪崩问题

一、Redis缓存 Redis是一个高性能的键值对存储数据库&#xff0c;也是一个基于内存的数据结构存储系统&#xff0c;同时也支持持久化数据存储。Redis提供了丰富的数据结构&#xff0c;包括字符串、哈希、列表、集合、有序集合等。在缓存方面&#xff0c;Redis最大的优点就是支持…

回避型人格适合什么职业?如何改善回避型人格?

回避型人格最突出的特点,就是对外界的排斥极度敏感&#xff0c;他们非常害怕别人的不认可&#xff0c;也特别害惧失败&#xff0c;因此不敢与人交往&#xff0c;同时也害怕新事物。因为受到这一性格的影响&#xff0c;他们极度缺乏社交能力&#xff0c;也一直在否定自身能力。 …

Flutter框架性泛学习系列之二、Flutter应用层(Application Layer)上-常用Widgets与简单动画

文章目录 概述一、应用程序&#xff08;Application&#xff09;&#xff1a;1、创建应用对象2、定义应用主页 二、Widgets&#xff1a;1. 基础的内置Widgets应用1.1 Text Widget1.2 RaisedButton Widget1.3 Image Widget1.4 Icon Widget 2. 自定义Widgets的创建与应用2.1 创建…

网络协议汇总

1.HTTP协议 1.认识URL 平时我们俗称的 "网址" 其实就是说的 URL URL中的字符只能是ASCII字符&#xff0c;但是ASCII字符比较少&#xff0c;而URL则常常包含ASCII字符集以外的字符&#xff0c;如非英语字符、汉字、特殊符号等等&#xff0c;所以要对URL进行转换。这个…

已解决Application run failed org.springframework.beans.factory.BeanNot

问题原因&#xff1a;SpringBoot的版本与mybiats-puls版本不对应且&#xff0c;spring自带的mybiats与mybiats-puls版本不对应 这里我用的是3.2.2版本的SpringBoot&#xff0c;之前mybiats-puls版本是3.5.3.1有所不同。 问题&#xff1a;版本对不上 解决办法&#xff1a;完整…

将JWT令牌存储到浏览器中localStorage中,并且往页面请求头中添加token

将JWT令牌存储到浏览器中localStorage中 localStorage.setItem(token, response.data.data) 其中response.data.data是后端返回的数据为jwt字符串 往页面请求头中添加token 在vue中的main.js添加如下再带&#xff0c;axios便会拦截所有请求并且如果localStorage有token则会…

宝塔nginx配置SpringBoot服务集群代理

宝塔nginx配置SpringBoot服务集群代理 1、需求&#xff1a; 现有一个springboot服务需要部署成集群&#xff0c;通过nginx负载均衡进行访问&#xff0c;其中这个springboot服务内置了MQTT服务、HTTP服务、TCP服务。 MQTT服务开放了1889端口 HTTP服务开放了8891端口 HTTP服务开…

LeetCode94.二叉树的中序遍历

题目 给定一个二叉树的根节点 root &#xff0c;返回 它的 中序 遍历 。 示例 &#xff1a; 输入&#xff1a;root [1,null,2,3] 输出&#xff1a;[1,3,2] 思路 中序遍历的顺序是左子树 -> 根节点 -> 右子树。因此&#xff0c;我们可以通过递归的方式遍历二叉树&…

《白话C++》第8章 8.4.1 INI文件简介,8.4.2面向过程的设计 Page 761

以下是一个INI例子文件的内容&#xff1a; [DISPLAY_SETTING] #是否显示启动窗口&#xff1a; will_show_splash_window yes default_title welcom... [NETWORK_SETTING] svc_host www.d2school.com svc_port 80 带中括号的行代表一个“配置段&#xff08;section&#x…

[word] word 怎样批量把英文单词的首字母全部改成大写 #笔记#其他#学习方法

word 怎样批量把英文单词的首字母全部改成大写 word在处理长文档的过程中&#xff0c;有时候一个单词在多页重复出现。如果要把该单词的首字母改成大写&#xff0c;如果一个一个的改&#xff0c;费时费力。 方法&#xff1a;替换功能 如&#xff1a;我要把camtasia批量改成C…

【riscv】使用qemu运行riscv裸机freestanding程序

文章目录 1. 运行显示2. 工具准备3. 裸机代码和编译3.1 源码3.2 编译 4. 使用qemu仿真运行riscv裸机程序 1. 运行显示 详见左下角&#xff0c; 运行时串口输出的字符 A ; 2. 工具准备 # for riscv64-linux-gnu-gcc sudo apt-get install gcc-riscv64-linux-gnu# for qemu-s…

P6279 题解

P6279 题解 Overview 结论&#xff08;待论证&#xff09; Description 给定一个有向图&#xff0c;这个有向图的每一个点所连接的点都属于同一个集合。 求集合数量最大且字典序最小的集合标号方案。 Solution 先讲结论。 结论&#xff1a;用 vector 存储每个点所连接的…