python爬虫---代理池搭建,爬取视频和新闻,BeautifulSoup4的使用

代理池搭建


我们使用爬虫爬取网页的可能会被封ip,根据ip限制频率。突破限制,每次发送请求使用代理ip,服务端封ip,只会限制代理ip。

基于网上别人开源的代理池的python代码,自己搭建(本质是爬取的免费代理,验证)

-基于flask搭建的服务端:提供一些接口,只要向接口发送请求,就能随机返回一个代理
-爬虫程序:爬取免费代理,验证通过放到redis中

第一步:clone代码

git clone git@github.com:jhao104/proxy_pool.git

第二步:安装依赖

pip3 install -r requirements.txt

第三步:配置配置文件

# settings.py
DB_CONN = 'redis://127.0.0.1:6379/1'

第四步:启动项目

# 爬虫程序
python38 proxyPool.py schedule
# web服务程序
python38 proxyPool.py server

第五步:获取代理

http://127.0.0.1:5010/get/

django后端获取客户端的ip

django 返回访问者ip,部署在服务器上

客户端使用搭建的代理池访问我们自己的djnago

-正常会返回代理的ip地址
    import requests
    res1 = requests.get('http://127.0.0.1:5010/get/').json()
    print(res1['proxy'])
    if res1['https']:
        h = 'https'
    else:
        h = 'http'

    proxies = {
       h: res1['proxy'],
    }
    res = requests.get('http://101.133.225.166/get_ip/',proxies=proxies)
    print('---',res.text)

爬取某视频网站


例子:爬取https://www.pearvideo.com/category_loading.jsp?reqType=5&categoryId=5&start=0

import requests
import re

res = requests.get('https://www.pearvideo.com/category_loading.jsp?reqType=5&categoryId=5&start=0')
# print(res.text)

video_list = re.findall('<a href="(.*?)" class="vervideo-lilink actplay">', res.text)
print(video_list)
# https://www.pearvideo.com/video_1768482
for video in video_list:
    video_id = video.split('_')[-1]
    video_url = 'https://www.pearvideo.com/' + video
    # 直接发送请求,拿不到视频,它是发送了ajax请求获取了视频,但是需要携带referer
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
        'Referer': video_url
    }
    res1 = requests.get('https://www.pearvideo.com/videoStatus.jsp?contId=%s&mrd=0.5602821872545047' % video_id,
                        headers=header
                        ).json()
    # print(res1['videoInfo']['videos']['srcUrl'])
    # https://video.pearvideo.com/mp4/third/20220729/     1659324669265     -11320310-183708-hd.mp4   # 不能播
# https://video.pearvideo.com/mp4/third/20220729/     cont-1768482      -11320310-183708-hd.mp4    #能播
    mp4_url = res1['videoInfo']['videos']['srcUrl']
    real_mp4_url = mp4_url.replace(mp4_url.split('/')[-1].split('-')[0], 'cont-%s' % video_id)
    print(real_mp4_url)
    # 下载视频
    res2 = requests.get(real_mp4_url)
    with open('video/%s.mp4' % video_id, 'wb') as f:
        for line in res2.iter_content(1024):
            f.write(line)

爬取新闻


re正则匹配:html内容(xml),比较复杂,查找的东西比较多

BeautifulSoup4 专业的对html,xml进行解析(修改)

安装

pip3 install beautifulsoup4

使用

import requests
from bs4 import BeautifulSoup

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

# print(res.text)
# 之前使用re解析,解析这个比较麻烦,我们使用bs4解析
#  第一个参数是要解析的字符串(html,xml格式)
#  第二个参数是解析方式:html.parser
soup = BeautifulSoup(res.text, 'html.parser')

# 开始使用,查找内容
# 查找所有的类名为article的ul标签
ul_list = soup.find_all(name='ul', class_='article')
for ul in ul_list:
    li_list = ul.find_all(name='li')
    for li in li_list:
        h3 = li.find(name='h3')
        if h3:
            # 从h3中取出文本内容,新闻标题
            title = h3.text
            desc = li.find(name='p').text
            # url=li.find(name='a')['href']
            url = 'http:' + li.find(name='a').attrs['href']
            img = 'http:' + li.find(name='img')['src']

            print('''
            新闻标题:%s
            新闻摘要:%s
            新闻地址:%s
            新闻图片:%s
            ''' % (title, desc, url,img))
            # 1 把图片保存到本地(你会)
            # 2 把清洗过后的数据存到mysql中
            # 3 全站爬取变更页码数(https://www.autohome.com.cn/news/1/#liststart)

BeautifulSoup4 介绍


Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库

使用requests发请求拿回来的html,就可以使用bs4解析出咱们想要的数据

BeautifulSoup(要解析的字符串, "解析方式:html.parser,lxml:需要安装lxml解析库,如果不装就报错")

文档容错能力:可以不是标准的html,缺一些标签,也可以解析

bs4 遍历文档树

数据准备

from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_p'>lqz is handsome<b>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>
"""

soup=BeautifulSoup(html_doc,'html.parser')
# print(soup.prettify())  # 美化html
使用

基本使用(通过 . 遍历,速度快)

 res=soup.p
 res1=soup.p.b
 res1=soup.html.body.p.b
 print(res1)

取标签的名称

res1=soup.body
print(res1.name)

获取标签的属性(两种方式)

 res1=soup.body.p
 # print(res1['class'])   # ['title']  因为class可能有多个
 # print(res1['id'])
 print(res1.attrs['id'])

 res=soup.a['href']
 print(res)

获取标签的内容

 res=soup.a
 print(res.text)  # text 把子子孙孙的文本内容拼到一起
 print(res.string) # string 没有子标签才能获取文本
 print(list(res.strings))  # generator strings:把子子孙孙的文本内容放到生成器中

 res=soup.p
 print(res.text)
 print(res.string)
 print(list(res.strings))

嵌套选择

因为soup.head那到的也是要给对象,bs4.element.Tag类的对象,因为BeautifulSoup继承子Tag

print(soup.head.title.string)
print(type(soup.head))

子节点、子孙节点

 print(soup.p.contents) # p下所有子节点
 print(soup.p.children) #得到一个迭代器,包含p下所有子节点
 print(list(soup.p.descendants)) #获取子孙节点,p下所有的标签都会选择出来

父节点、祖先节点

 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(list(soup.a.previous_siblings)) #上面的兄弟们=>生成器对象

bs4搜索文档树

数据准备

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_p'>lqz is handsome<b class='sister'>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>
"""

soup = BeautifulSoup(html_doc, 'html.parser')
使用

find(找最近的一个),find_all(找所有符合的)

五种过滤器: 字符串、正则表达式、列表、True、方法

字符串--->字符串指的是属性是字符串

 p=soup.find(name='p',class_='title')
 p=soup.find(id='id_p')
 p=soup.find(id='id_p')
 res=soup.find(text="The Dormouse's story").parent
 print(res)

正则表达式

 import re
 # res=soup.find_all(name=re.compile('^b'))
 res=soup.find_all(class_=re.compile('^s'))
 print(res)

列表

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

True

 res=soup.find_all(id=True)  # 有id的所有标签
 res=soup.find_all(text=False)
 print(res)

方法

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

 print(soup.find_all(name=has_class_but_no_id))

find_all的其它属性:find就是find_all,只不过取了第一条

# limit:限制取的条数
 res=soup.find_all(class_=True,limit=1)
# recursive:是否递归查找,找一层还是找多层
 res=soup.body.find_all(name='p',recursive=False)

# attrs
 res=soup.find_all(class_=True)
 res=soup.find_all(attrs={'class':True})
 print(res)

css选择器

# 还可以使用css选择器
'''
div    标签名
.类名   类名
#id     id号
div>p   div下紧邻的p标签
div p   div下子子孙孙有p就拿出来

'''
# res=soup.select('.sister')
# res=soup.select('b.sister')
res=soup.select('#id_p')[0]['class']
print(res)
posted @ 2022-08-01 20:05  早安_1207  阅读(266)  评论(0)    收藏  举报
返回顶端