数据抓取-bs4、XPath、pyquery详细代码演示

news2024/7/4 5:31:51

数据抓取-bs4、XPath、pyquery

一般抓取某个网站或者某个应用的内容,内容分为两个部分

  • 非结构化的文本:HTML文本

  • 结构化的文本:JSON、XML

非结构化的数据常见的解析方式有:XPath、CSS选择器、正则表达式

XPath语言

XPath是XML路径语言,他是一种用来定位XML文档中的某部分位置的语言

将HTML转换成XML文档之后,用XPath查找HTML节点或元素

比如用"来作为上下层级间的分隔,第一个"/"表示文档的根节点(注意,不是指文档最外层的tag节点,而是指文档本身)。

比如对于一个HTML文件来说,最外层的节点应该是"/html"。

XPath语法

Xpath是一门在XML文档中查找信息的语言。

XPath 可用来在XML文档中对元素和属性进行遍历。

选取节点 XPath使用路径表达式在XML文档中选取节点。节点是通过沿着路径或者step来选取的。

下面列出了最有用的路径表达式:

在这里插入图片描述

在下面列举出一些路径表达式以及表达式结果

在这里插入图片描述

安装XPath库

首先在终端中pip install lxml ,然后对XPath库进行import

from lxml import html  # XPath包

代码演示

我们对下面这个网站进行爬取

https://www.fabiaoqing.com/

首先要构建一个模板

import requests

url = ''
headers = {

}
response = requests.get(url,headers=headers).text

下面我们需要得到里面一张图片的地址,通过F12来定位图片所在路径

在这里插入图片描述

打开源代码,搜索上面那个网页路径,如果在源代码中包含的话,说明这张图片是静态数据,得到这张图片的地址,放入代码url

之后我们来寻找headers,通过F12来获取,放入代码headers

在这里插入图片描述

由于是图片返回的内容,所以我们将text换成content

之后导入os库来显示图片的保存

import requests
import os
#路径保存
path = './images/'
count = 1

url = 'http://tva3.sinaimg.cn/large/006D3Lhmgy1h4eqp9hggjj30go0gwq3l.jpg'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
}
response = requests.get(url, headers=headers).content

if not os.path.exists(path):
    os.makedirs(path)
with open(path + "{}.jpg".format(count),'ab') as f:
    f.write(response)

就可以将爬的图片存到文件夹中

在这里插入图片描述

以上就是完成一张 图片爬取的过程


下面我们对代码进行封装:文件储存和文件请求

  • 文件请求
def Tools(url):
    '''
    请求工具函数
    :param url:请求地址
    :return:响应状态
    '''
    # url = 'http://tva3.sinaimg.cn/large/006wuNILly1h3zb9wkxf7j30jg0jgq4l.jpg'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
    }
    # response = requests.get(url, headers=headers).content
    response = requests.get(url, headers=headers)
    return response


  • 文件存储
def Save(img_url):
    '''
    存储图片
    :param img_url: 图片地址
    :return: None
    '''
    count = 1
    response = Tools(img_url).content
    if not os.path.exists(path):
        os.makedirs(path)
    with open(path + "{}.jpg".format(count), 'ab') as f:
        f.write(response)

导入lxml库之后,我们需要对response转成xml的格式,由于原来的response格式是string类型

url = 'https://www.fabiaoqing.com/biaoqing/detail/id/681814.html'
response = Tools(url).text # 静态页面内容
print(type(response))
#------运行结果----------
<class 'str'>

我们创建一个xml的对象来转换格式

xml1 = html.etree.HTML(response)
print(type(xml1))
# ------运行结果-------
<class 'lxml.etree._Element'>

#------------------------------
# 创建一个lxml对象
xml1 = html.etree.HTML(response)
img_url = xml1.xpath() #使用相对路径

XPath也分为相对路径和绝对路径

xpath缺点:如果查询路径下面存在其他内容,就会返回元素得内存地址,需要遍历

xml1 = html.etree.HTML(response)
print(xml1)
# ------运行结果----------
<Element html at 0x17197980ac0>
img_url = xml1.xpath('//img[@class="biaoqingpp"]/@src') [0] # xpath缺点:如果查询路径下面存在其他内容,就会返回元素得内存地址,需要遍历
print(img_url)
# ---------运行结果-----------
http://tva3.sinaimg.cn/large/006wuNILly1h3zb9wkxf7j30jg0jgq4l.jpg

我们现在想要得到一系列得图片地址,所以我们将url替换

这里我们使用pyquery库

pyquery库安装

pip install pyquery
from pyquery import PyQuery as pq  # 简单快捷

  • 在寻找数据标签提取的时候,但是没有可选属性(calss id)找上级 属性是否存在,一般是带有属性的标签才是可选的

当存在class拥有多个属性的时候,xpath可以

xpath:[@class="swiper-slide swiper-slide-active bqpp"] 多个属性

而pyquery更侧重于选择器为主

url = 'https://www.fabiaoqing.com/bqb/detail/id/54891.html'
response = Tools(url).text
doc = pq(response) # 创建一个pyquery对象
# id选择器 #
# class选择器 .
# 如果存在多个 空格换成对于的选择器方式
# 想要选择下级的内容 用空格分割
detail =doc('.swiper-slide.swiper-slide-active.bqpp a')
print(detail)
# ------------------运行结果----------------------
<a href="/biaoqing/detail/id/681278.html" title="&#x65E9;&#x4E0A;&#x597D;,&#x6211;&#x7684;&#x5DE5;&#x53CB;"/><a href="/biaoqing/detail/id/681279.html" title="&#x5982;&#x679C;&#x7231;&#x8BF7;&#x6253;&#x94B1;"/><a href="/biaoqing/detail/id/681280.html" title="&#x5475;&#x5475;&#x6813;Q"/><a href="/biaoqing/detail/id/681281.html" title="&#x731B;&#x72D7;&#x54ED;&#x6CE3;"/>
<a href="/biaoqing/detail/id/681282.html" title="&#x6491;&#x4F1E;??&#x6211;&#x8BA9;&#x4F60;&#x6491;&#x4F1E;!"/>
<a href="/biaoqing/detail/id/681283.html" title="&#x8DEA;&#x4E0B;&#x4E3E;&#x624B;&#x4E0D;&#x6740;"/>
<a href="/biaoqing/detail/id/681284.html" title="&#x8D77;&#x4E0D;&#x6765;&#x5E8A;"/>
<a href="/biaoqing/detail/id/681285.html" title="&#x600E;&#x4E48;&#x4E86;?&#x4E0D;&#x56DE;&#x4F60;&#x6D88;&#x606F;&#x591A;&#x6B63;&#x5E38;&#x554A;&#x4F60;&#x770B;&#x54EA;&#x4E2A;&#x7F8E;&#x5973;&#x4E0D;&#x5FD9;&#x7684;"/>
<a href="/biaoqing/detail/id/681286.html" title="&#x8001;&#x5B50;&#x6234;&#x4E2A;&#x8001;&#x82B1;&#x955C;&#x90FD;&#x770B;&#x4E0D;&#x6E05;&#x4F60;&#x4E2A;&#x827E;&#x65AF;&#x81C2;"/>
<a href="/biaoqing/detail/id/681287.html" title="&#x90A3;&#x4F60;&#x62A5;&#x8B66;&#x561B;"/>
<a href="/biaoqing/detail/id/681288.html" title="&#x629B;&#x5F00;&#x5185;&#x5BB9;&#x4E0D;&#x8C08;&#x4F60;&#x8BF4;&#x7684;&#x5F88;&#x6709;&#x9053;&#x7406;"/>
<a href="/biaoqing/detail/id/681289.html" title="&#x4E0D;&#x77E5;&#x9053;&#x4E3A;&#x4EC0;&#x4E48;&#x5C31;&#x662F;&#x4E0D;&#x60F3;&#x5E72;&#x4E86;"/>
<a href="/biaoqing/detail/id/681290.html" title="&#x6211;&#x6CA1;&#x60F9;&#x4F60;&#x4EEC;&#x4EFB;&#x4F55;&#x4EBA;&#x57AE;&#x5C0F;&#x8138;"/>
                                            

变为元素地址

detail =[i for i in doc('.swiper-slide.swiper-slide-active.bqpp a')]  # 变为元素地址
print(detail)
# ------------------运行结果----------------------
[<Element a at 0x1e52f54b770>, <Element a at 0x1e52f54b270>, <Element a at 0x1e52f54b360>, <Element a at 0x1e52f54b130>, <Element a at 0x1e52f54b180>, <Element a at 0x1e52f54b4a0>, <Element a at 0x1e52f54b400>, <Element a at 0x1e52f54b0e0>, <Element a at 0x1e52f54b090>, <Element a at 0x1e52f54b7c0>, <Element a at 0x1e52f54b680>, <Element a at 0x1e52f54b810>, <Element a at 0x1e52f54b860>]


返回查询对象

detail =doc('.swiper-slide.swiper-slide-active.bqpp a').items() # 返回查询对象
for i in detail :
    print(i)
# ------------------运行结果----------------------
<a href="/biaoqing/detail/id/681278.html" title="&#x65E9;&#x4E0A;&#x597D;,&#x6211;&#x7684;&#x5DE5;&#x53CB;"/>
                                            
<a href="/biaoqing/detail/id/681279.html" title="&#x5982;&#x679C;&#x7231;&#x8BF7;&#x6253;&#x94B1;"/>
                                            
<a href="/biaoqing/detail/id/681280.html" title="&#x5475;&#x5475;&#x6813;Q"/>
                                            
<a href="/biaoqing/detail/id/681281.html" title="&#x731B;&#x72D7;&#x54ED;&#x6CE3;"/>
                                            
<a href="/biaoqing/detail/id/681282.html" title="&#x6491;&#x4F1E;??&#x6211;&#x8BA9;&#x4F60;&#x6491;&#x4F1E;!"/>
                                            
<a href="/biaoqing/detail/id/681283.html" title="&#x8DEA;&#x4E0B;&#x4E3E;&#x624B;&#x4E0D;&#x6740;"/>
                                            
<a href="/biaoqing/detail/id/681284.html" title="&#x8D77;&#x4E0D;&#x6765;&#x5E8A;"/>
                                            
<a href="/biaoqing/detail/id/681285.html" title="&#x600E;&#x4E48;&#x4E86;?&#x4E0D;&#x56DE;&#x4F60;&#x6D88;&#x606F;&#x591A;&#x6B63;&#x5E38;&#x554A;&#x4F60;&#x770B;&#x54EA;&#x4E2A;&#x7F8E;&#x5973;&#x4E0D;&#x5FD9;&#x7684;"/>
                                            
<a href="/biaoqing/detail/id/681286.html" title="&#x8001;&#x5B50;&#x6234;&#x4E2A;&#x8001;&#x82B1;&#x955C;&#x90FD;&#x770B;&#x4E0D;&#x6E05;&#x4F60;&#x4E2A;&#x827E;&#x65AF;&#x81C2;"/>
                                            
<a href="/biaoqing/detail/id/681287.html" title="&#x90A3;&#x4F60;&#x62A5;&#x8B66;&#x561B;"/>
                                            
<a href="/biaoqing/detail/id/681288.html" title="&#x629B;&#x5F00;&#x5185;&#x5BB9;&#x4E0D;&#x8C08;&#x4F60;&#x8BF4;&#x7684;&#x5F88;&#x6709;&#x9053;&#x7406;"/>
                                            
<a href="/biaoqing/detail/id/681289.html" title="&#x4E0D;&#x77E5;&#x9053;&#x4E3A;&#x4EC0;&#x4E48;&#x5C31;&#x662F;&#x4E0D;&#x60F3;&#x5E72;&#x4E86;"/>
                                            
<a href="/biaoqing/detail/id/681290.html" title="&#x6211;&#x6CA1;&#x60F9;&#x4F60;&#x4EEC;&#x4EFB;&#x4F55;&#x4EBA;&#x57AE;&#x5C0F;&#x8138;"/>


接着我们取出href标签

完整代码如下:就可以爬取二级页面内的图片放入文件夹

import requests
import os
from lxml import html  # XPath包 定位精准
from pyquery import PyQuery as pq  # 简单快捷 选择器为主


def Tools(url):
    '''
    请求工具函数
    :param url:请求地址
    :return:响应状态
    '''
    # url = 'http://tva3.sinaimg.cn/large/006wuNILly1h3zb9wkxf7j30jg0jgq4l.jpg'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
    }
    # response = requests.get(url, headers=headers).content
    response = requests.get(url, headers=headers)
    return response


# 全局变量
path = './images/'
count = 1


def Save(img_url):
    """
    存储图片
    :param img_url: 图片地址
    :return: None
    """
    global count
    response = Tools(img_url).content
    # 判断path是否存在
    if not os.path.exists(path):
        os.makedirs(path)  # 如果不存在就创建 递归创建
    # with 写入方法 w:不存在就覆盖创建(文件) a: 追加模式
    with open(path + "{}.jpg".format(count), 'ab') as f:
        f.write(response)
    count += 1


def Details(detail):
    """
    xpath学习 提取 图片地址
    :param detail:详情页后缀
    :return:None
    """
    url = 'https://www.fabiaoqing.com{}'.format(detail)
    response = Tools(url).text
    # 创建一个lxml对象
    xml1 = html.etree.HTML(response)
    # xpath:[@class="swiper-slide swiper-slide-active bqpp"] 多个属性
    # 从哪里开始,例如(//img)[@选择一个属性] id/class 都是属性  / 下级  包含里面也是下级
    img_url = xml1.xpath('//img[@class="biaoqingpp"]/@src')[0]
    Save(img_url)


def Bqp():
    """
    二级页面 主要是获取详情页后缀
    :return:None
    """

    url = 'https://www.fabiaoqing.com/bqb/detail/id/54891.html'
    response = Tools(url).text
    doc = pq(response)  # 创建一个pyquery对象
    # id选择器 #
    # class选择器 .
    # 如果存在多个 空格换成对于的选择器方式
    # 想要选择下级的内容 用空格分割
    # detail = [i for i in doc('.swiper-slide.swiper-slide-active.bqpp a')]  # 变为元素地址
    # print(detail)
    detail = doc('.swiper-slide.swiper-slide-active.bqpp a').items()  # 返回查询对象
    for i in detail:
        href = i.attr('href')  # attr 属性的获取
        Details(href)

Bqp()

保存的图片都存放在image文件夹中

在这里插入图片描述


bs4应用和Beautiful Soup

  • 安装
pip install bs4
from bs4 import BeautifulSoup

现在我们需要在一级页面内爬取二级页面的内容

BeautifulSoup 就是 Python 的一个 HTML 或 XML 的解析库。

  • 提供了一些简单的方法。编写应用程序所需的代码不多

  • 自动将传入的文档转换为Unicode,将传出的文档转换为UTF-8。然后,您只需指定原始的编码

  • 位于流行的Python解析器之上,比如lxml和html5lib。

具体beautifulsoup库的知识可以看一下下面的网址

https://aistudio.csdn.net/62e38a76cd38997446774c98.html?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2~default~BlogCommendFromBaidu~activity-1-81171951-blog-100668663.pc_relevant_vip_default&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2~default~BlogCommendFromBaidu~activity-1-81171951-blog-100668663.pc_relevant_vip_default&utm_relevant_index=1

使用了这个工具可以进行解析,直接找到元素内容

在这里插入图片描述

def Twelve():
    url = 'https://www.fabiaoqing.com/bqb/lists/type/doutu.html'
    response = Tools(url).text
    soup = BeautifulSoup(response,'lxml') # 解析对象
    items = soup.find('div',{'class':'ui segment'}).find_all('div',{'class':'bqppdiv'})
    print(items)

Twelve()
# ------------------运行结果----------------------
[<div class="bqppdiv" style="vertical-align:middle;">
<img alt="FUCK,艹 - 唐僧系列表情包:你们再给贫僧瞎配字,老子喷掉你妈的远古巨坟_唐僧_妈卖批_装逼_斗图表情-发表情" class="ui image lazy" data-original="http://tva3.sinaimg.cn/bmiddle/415f82b9ly1faxk6dg7ddj20ku0i71kx0.jpg" src="/Public/lazyload/img/transparent.gif" style="max-height: 170;max-width: 100%;margin: 0 auto"/> <p style="display: block;height: 0;width: 0;overflow: hidden;">FUCK,艹 - 唐僧系列表情包:你们再给贫僧瞎配字,老子喷掉你妈的远古巨坟_唐僧_妈卖批_装逼_斗图表情</p>
</div>, <div class="bqppdiv" style="vertical-align:middle;">
<img alt="再装逼怼死你 - 唐僧系列表情包:你们再给贫僧瞎配字,老子喷掉你妈的远古巨坟_唐僧_妈卖批_装逼_斗图表情-发表情" class="ui image lazy" data-original="http://tva3.sinaimg.cn/bmiddle/415f82b9ly1faxk70o0jyj20ku0i71kx0.jpg" src="/Public/lazyload/img/transparent.gif" style="max-height: 170;max-width: 100%;margin: 0 auto"/> <p style="display: block;height: 0;width: 0;overflow: hidden;">再装逼怼死你 - 唐僧系列表情包:你们再给贫僧瞎配字,老子喷掉你妈的远古巨坟_唐僧_妈卖批_装逼_斗图表情</p>
</div>, <div class="bqppdiv" style="vertical-align:middle;">
<img alt="火冒三藏(火冒三丈) - 唐僧系列表情包:你们再给贫僧瞎配字,老子喷掉你妈的远古巨坟_唐僧_妈卖批_装逼_斗图表情-发表情" class="ui image lazy" data-original="http://tva3.sinaimg.cn/bmiddle/415f82b9ly1faxk7cip2oj20dw0dwwg30.jpg" src="/Public/lazyload/img/transparent.gif" style="max-height: 170;max-width: 100%;margin: 0 auto"/> <p style="display: block;height: 0;width: 0;overflow: hidden;">火冒三藏(火冒三丈) - 唐僧系列表情包:你们再给贫僧瞎配字,老子喷掉你妈的远古巨坟_唐僧_妈卖批_装逼_斗图表情</p>
</div>, <div class="bqppdiv" style="vertical-align:middle;">
<img alt="是为师错怪你了,但那又如何 - 唐僧系列表情包:你们再给贫僧瞎配字,老子喷掉你妈的远古巨坟_唐僧_妈卖批_装逼_斗图表情-发表情" class="ui image lazy" data-original="http://tva3.sinaimg.cn/bmiddle/415f82b9ly1faxmjfcr3xj20ku0i71kx0.jpg" src="/Public/lazyload/img/transparent.gif" style="max-height: 170;max-width: 100%;margin: 0 auto"/> <p style="display: block;height: 0;width: 0;overflow: hidden;">是为师错怪你了,但那又如何 - 唐僧系列表情包:你们再给贫僧瞎配字,老子喷掉你妈的远古巨坟_唐僧_妈卖批_装逼_斗图表情</p>
</div>, <div class="bqppdiv notshowinpc" style="vertical-align:middle;">
<img alt="我 TMD 没说过这句话 - 唐僧系列表情包:你们再给贫僧瞎配字,老子喷掉你妈的远古巨坟_唐僧_妈卖批_装逼_斗图表情-发表情" class="ui image lazy" data-original="http://tva3.sinaimg.cn/bmiddle/415f82b9ly1faxmjesozvj20ku0i71kx0.jpg" src="/Public/lazyload/img/transparent.gif" style="max-height: 170;max-width: 100%;margin: 0 auto"/> <p style="display: block;height: 0;width: 0;overflow: hidden;">我 TMD 没说过这句话 - 唐僧系列表情包:你们再给贫僧瞎配字,老子喷掉你妈的远古巨坟_唐僧_妈卖批_装逼_斗图表情</p>
</div>]

如果我们想要得到里面的属性

在这里插入图片描述

items = soup.find('a',{'class':'bqba'}).get('href')
print(items)
# --------------运行结果-------------------
/bqb/detail/id/9825.html

想要批量得到数据就要对代码进行修改,得到后缀地址

items = soup.find_all('a',{'class':'bqba'})
    for i in items:
        print(i.get('href'))

# --------------运行结果-------------------
/bqb/detail/id/9825.html
/bqb/detail/id/20585.html
/bqb/detail/id/30834.html
/bqb/detail/id/30739.html
/bqb/detail/id/51396.html
/bqb/detail/id/51206.html
/bqb/detail/id/51449.html
/bqb/detail/id/51355.html
/bqb/detail/id/51431.html
/bqb/detail/id/39818.html

下面展示爬取页面的完整代码

import requests
import os
from lxml import html  # XPath包 定位精准
from pyquery import PyQuery as pq  # 简单快捷 选择器为主
from bs4 import BeautifulSoup


def Tools(url):
    '''
    请求工具函数
    :param url:请求地址
    :return:响应状态
    '''
    # url = 'http://tva3.sinaimg.cn/large/006wuNILly1h3zb9wkxf7j30jg0jgq4l.jpg'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
    }
    # response = requests.get(url, headers=headers).content
    response = requests.get(url, headers=headers)
    return response


# 全局变量
path = './images/'
count = 1


def Save(img_url):
    """
    存储图片
    :param img_url: 图片地址
    :return: None
    """
    global count
    response = Tools(img_url).content
    # 判断path是否存在
    if not os.path.exists(path):
        os.makedirs(path)  # 如果不存在就创建 递归创建
    # with 写入方法 w:不存在就覆盖创建(文件) a: 追加模式
    with open(path + "{}.jpg".format(count), 'ab') as f:
        f.write(response)
    count += 1


def Details(detail):
    """
    xpath学习 提取 图片地址
    :param detail:详情页后缀
    :return:None
    """
    url = 'https://www.fabiaoqing.com{}'.format(detail)
    response = Tools(url).text
    # 创建一个lxml对象
    xml1 = html.etree.HTML(response)
    # xpath:[@class="swiper-slide swiper-slide-active bqpp"] 多个属性
    # 从哪里开始,例如(//img)[@选择一个属性] id/class 都是属性  / 下级  包含里面也是下级
    img_url = xml1.xpath('//img[@class="biaoqingpp"]/@src')[0]
    print('img:', img_url)
    Save(img_url)


def Bqp(id1):
    """
    二级页面 主要是获取详情页后缀
    :return:None
    """

    url = 'https://www.fabiaoqing.com{}'.format(id1)
    response = Tools(url).text
    doc = pq(response)  # 创建一个pyquery对象
    # id选择器 #
    # class选择器 .
    # 如果存在多个 空格换成对于的选择器方式
    # 想要选择下级的内容 用空格分割
    # detail = [i for i in doc('.swiper-slide.swiper-slide-active.bqpp a')]  # 变为元素地址
    # print(detail)
    detail = doc('.swiper-slide.swiper-slide-active.bqpp a').items()  # 返回查询对象
    for i in detail:
        href = i.attr('href')  # attr 属性的获取
        Details(href)


def Twelve():
    url = 'https://www.fabiaoqing.com/bqb/lists/type/doutu.html'
    response = Tools(url).text
    soup = BeautifulSoup(response,'lxml') # 解析对象
    # items = soup.find('div',{'class':'ui segment'}).find_all('div',{'class':'bqppdiv'})
    items = soup.find_all('a',{'class':'bqba'})
    for i in items:
        pid1 = i.get('href')
        Bqp(pid1)
    # print(items)
Twelve()


# ---------------运行结果-------------------------
img: http://tva3.sinaimg.cn/large/415f82b9ly1faxk6dg7ddj20ku0i71kx0.jpg
img: http://tva3.sinaimg.cn/large/415f82b9ly1faxk70o0jyj20ku0i71kx0.jpg
img: http://tva3.sinaimg.cn/large/415f82b9ly1faxk7cip2oj20dw0dwwg30.jpg
img: http://tva3.sinaimg.cn/large/415f82b9ly1faxmjfcr3xj20ku0i71kx0.jpg
img: http://tva3.sinaimg.cn/large/415f82b9ly1faxmjesozvj20ku0i71kx0.jpg
img: http://tva3.sinaimg.cn/large/cf652d2bgy1fet5axr3aqg205k05k76n.gif
img: http://tva3.sinaimg.cn/large/cf652d2bgy1fet5ay4tw8g205k05kmzi.gif
img: http://tva3.sinaimg.cn/large/cf652d2bgy1fet5aykcxig205k05kgnz.gif
img: http://tva3.sinaimg.cn/large/cf652d2bgy1fet5ayu2tcg205k05k0v3.gif
img: http://tva3.sinaimg.cn/large/cf652d2bgy1fet5az9400g205k05k0v3.gif
img: http://tva3.sinaimg.cn/large/cf652d2bgy1fet5azk1dpg205k05ktb2.gif
img: http://tva3.sinaimg.cn/large/cf652d2bgy1fet5azuzebg205k05kwgu.gif
img: http://tva3.sinaimg.cn/large/cf652d2bgy1fet5b099i7g205k05kacg.gif
img: http://tva3.sinaimg.cn/large/cf652d2bgy1fet5b0lfoug205k05kq5a.gif
img: http://tva3.sinaimg.cn/large/a9cf8ef6ly1fiecn56l8wj20b50b2glu.jpg
img: http://tva3.sinaimg.cn/large/a9cf8ef6ly1fiecn5kfa1j20b50b274n.jpg
img: http://tva3.sinaimg.cn/large/a9cf8ef6ly1fiecn5to8ej20b50b2aad.jpg
img: http://tva3.sinaimg.cn/large/a9cf8ef6ly1fiecn62tbbj20b50b2jrs.jpg
img: http://tva3.sinaimg.cn/large/a9cf8ef6ly1fiecn6dfkij20b50b2wes.jpg
img: http://tva3.sinaimg.cn/large/a9cf8ef6ly1fiecn6plqvj20b50b2t9l.jpg
img: http://tva3.sinaimg.cn/large/a9cf8ef6ly1fiecn4v8maj20b50b2jro.jpg
img: http://tva3.sinaimg.cn/large/006fbYi5gy1fid8qw20afj308c06s74c.jpg
img: http://tva3.sinaimg.cn/large/006fbYi5gy1fid8qw8wtxj304z04oa9z.jpg
img: http://tva3.sinaimg.cn/large/006fbYi5gy1fid8qwjf87j30hs0ef74x.jpg
img: http://tva3.sinaimg.cn/large/006fbYi5gy1fid8qvux8mj305i04vdfs.jpg
img: http://tva3.sinaimg.cn/large/006fbYi5gy1fid8qwt2b5j303302bmx0.jpg
img: http://tva3.sinaimg.cn/large/006fbYi5gy1fid8qwzj5qj303302b3yb.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxmsggpt4nj30k00hotai.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxmqhprkcqj30u00u0wgb.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxmt7u5issj302o02qmx7.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxmsvkpnxjj30at0ay757.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxmqhqfaruj30dw0iqgno.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxmr7l0r74j305i058wf4.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxmsg31068j3048048dgc.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxmraxkj4oj304g03u0ss.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxmr7kt7uij308k0afwf6.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fwqhawt334j30k00n0485.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fwq1v50u6jj30k00k0ac4.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fwqj2l6gwcj30ik0m70ug.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fwqg6p42p9j307i08iq3a.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fwr345nafcj30j60hwtgw.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fwq1wu0fgmj30fd0fdgm6.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fwqfkdkpyqj30hs0hst9j.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fwq1v4f8t2j30c80bzjrt.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxtf8kfkerj30j60kedh8.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxtbp3utemj30go0go74x.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxtoo6bha3j30v91by7l6.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxtrcwlb3mj302t03ct8u.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxtdenusy1j30go0dudjy.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxtf84o9y6j30j60hwtcn.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxtf84twtbj30c20c0my8.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxtp35bi77j315o15o4qp.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxtpnqqrsxj30u00u0gsq.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxgphl6w5oj30v80n4adz.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxh2npx2bwj307i07j751.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxh17465kfj307i07imyf.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxgphklbw4j30hs0dsgmn.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxgphwjmp1j30go0go0u5.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxgyyyuaz4j30jg0fota8.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxh1p1ewbuj306o06ojsa.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxgyyyph5rj30qo0qon4b.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxriyq4uohj30hz0hzn8f.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxrftk0gu9j302e01xdfu.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxrhbgm8xqj30hg0gzgnl.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxrfis81f2j30ti0ti78c.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxpwoybmlmj305i05cdg3.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxri0qt2ddj30k00sfadq.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxrjmjo6u1j30qo0q9jsl.jpg
img: http://tva3.sinaimg.cn/large/006m97Kgly1fxq9fbvdb3j31500u0whw.jpg
img: http://tva3.sinaimg.cn/large/415f82b9ly1flhn08nfh2j20ii0hsq3v.jpg
img: http://tva3.sinaimg.cn/large/415f82b9ly1flhn0a3ko7j20hs0hsjsa.jpg
img: http://tva3.sinaimg.cn/large/415f82b9ly1flhn06yjoej20hs0gygn0.jpg
img: http://tva3.sinaimg.cn/large/415f82b9ly1flhn08g4pxj20go0gcjsy.jpg
img: http://tva3.sinaimg.cn/large/415f82b9ly1flhn06lxbpj20ku0l6whm.jpg
img: http://tva3.sinaimg.cn/large/415f82b9ly1flhn0binx2j20kt0kqaby.jpg
img: http://tva3.sinaimg.cn/large/415f82b9ly1flhn07ibb3j20hs0hs3zt.jpg
img: http://tva3.sinaimg.cn/large/415f82b9ly1flhn0u67qyj20re0qogns.jpg


静态页面中不同页数的爬取

在静态页面中不同页面的区别只是换了不同的html,例如下面是第一页和第二页

在这里插入图片描述

我们对代码进行修改来爬取整个页面的图片

import requests
import os
from lxml import html  # XPath包 定位精准
from pyquery import PyQuery as pq  # 简单快捷 选择器为主
from bs4 import BeautifulSoup


def Tools(url):
    '''
    请求工具函数
    :param url:请求地址
    :return:响应状态
    '''
    # url = 'http://tva3.sinaimg.cn/large/006wuNILly1h3zb9wkxf7j30jg0jgq4l.jpg'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
    }
    # response = requests.get(url, headers=headers).content
    response = requests.get(url, headers=headers)
    return response


# 全局变量
path = './images/'
count = 1


def Save(img_url):
    """
    存储图片
    :param img_url: 图片地址
    :return: None
    """
    global count
    response = Tools(img_url).content
    # 判断path是否存在
    if not os.path.exists(path):
        os.makedirs(path)  # 如果不存在就创建 递归创建
    # with 写入方法 w:不存在就覆盖创建(文件) a: 追加模式
    with open(path + "{}.gif".format(count), 'ab') as f:
        f.write(response)
    count += 1


def Details(detail):
    """
    xpath学习 提取 图片地址
    :param detail:详情页后缀
    :return:None
    """
    url = 'https://www.fabiaoqing.com{}'.format(detail)
    response = Tools(url).text
    # 创建一个lxml对象
    xml1 = html.etree.HTML(response)
    # xpath:[@class="swiper-slide swiper-slide-active bqpp"] 多个属性
    # 从哪里开始,例如(//img)[@选择一个属性] id/class 都是属性  / 下级  包含里面也是下级
    img_url = xml1.xpath('//img[@class="biaoqingpp"]/@src')[0]
    print('img:', img_url)
    Save(img_url)


def Bqp(id1):
    """
    二级页面 主要是获取详情页后缀
    :return:None
    """

    url = 'https://www.fabiaoqing.com{}'.format(id1)
    response = Tools(url).text
    doc = pq(response)  # 创建一个pyquery对象
    # id选择器 #
    # class选择器 .
    # 如果存在多个 空格换成对于的选择器方式
    # 想要选择下级的内容 用空格分割
    # detail = [i for i in doc('.swiper-slide.swiper-slide-active.bqpp a')]  # 变为元素地址
    # print(detail)
    detail = doc('.swiper-slide.swiper-slide-active.bqpp a').items()  # 返回查询对象
    for i in detail:
        href = i.attr('href')  # attr 属性的获取
        Details(href)


def Twelve(page, type1):
    """
    首页请求获取二级页面数据
    :param page:分页
    :param type1:图片类型
    :return:None
    """
    url = 'https://www.fabiaoqing.com/bqb/lists/type/{}/page/{}.html'.format(type1, page)
    response = Tools(url).text
    soup = BeautifulSoup(response, 'lxml')  # 解析对象
    # items = soup.find('div',{'class':'ui segment'}).find_all('div',{'class':'bqppdiv'})
    items = soup.find_all('a', {'class': 'bqba'})
    for i in items:
        pid1 = i.get('href')
        Bqp(pid1)
    # print(items)


def main():
    url = 'https://www.fabiaoqing.com/bqb/lists/type/doutu.html'
    response = Tools(url).text
    # 使用pyquery
    doc = pq(response)
    item = doc('.ui.secondary.pointing.blue.menu a').items()
    for i, page in zip(item, range(1, 10)):
        href = i.attr('href').split('/')[4].split('.')[0]
        # print(href)
        Twelve(page,href)


if __name__ == '__main__':
    main()

运行的结果就是爬取了500多张的图片

在这里插入图片描述

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

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

相关文章

golang知识点整理

目录 1、goroutine GMP模型 2、goroutine阻塞的处理 3、goroutine内存泄漏 4、map原理、扩容 5、go内存管理 6、go的gc 1、goroutine GMP模型 1. G代表一个goroutine对象&#xff0c;每次go调用的时候&#xff0c;都会创建一个G对象 2. M代表一个线程&#xff0c;每次创建…

JavaScript和Node.js的关系

JavaScript和Node.js的关系 JavaScript是一门编程语言&#xff08;脚本语言&#xff09;&#xff0c;JavaScript以前是在浏览器里执行的&#xff0c;需要浏览器里的JavaScript引擎&#xff0c;Firefox有叫做Spidermonkey的引擎&#xff0c;Safari有JavaScriptCore的引擎&#x…

第2章物理层——2.数据通信基础知识

一.数据通信系统模型 一个通信系统可以划分为三大部分: 源系统&#xff08;发送端&#xff09;&#xff0c;传输系统&#xff08;传输网络&#xff09;&#xff0c;目的系统&#xff08;接收端&#xff09; [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传…

GIS工具maptalks开发手册(二)03-02——示例之json格式添加绘制工具、渲染点、文字和多个面

GIS工具maptalks开发手册(二)03-02——示例之json格式添加绘制工具、渲染点、文字和多个面 layer参数——https://maptalks.org/maptalks.js/api/0.x/Layer.html 1、json格式渲染点和面 效果-json格式渲染点和面 代码 index.html <!DOCTYPE html> <html> <…

spring boot使用自定义过滤器实现接口认证

spring boot使用自定义过滤器实现接口认证自定义过滤器创建FilterConfig类加密 解密 验证CipherFilter其他工具类AES 128 加密工具bean未加载前获取bean接口效果swagger访问Apipost 错误请求Apipost 正确请求自定义过滤器 创建MyFilter 类 去实现Filter接口 根据业务逻辑&…

(Git) git使用入门学习

文章目录打开基本操作拉代码常用指令设置用户查看历史版本分支管理配置公钥基于VS CodeEND打开 Git Bash Here 即打开命令行的形式 基本操作 拉代码 # git clone 地址 $ git clone https://gitee.com/heaven-sent-lotus/test.git常用指令 # 查看状态 git status# 添加到工作区…

数学建模学习(109):几行代码训练几十种机器学习模型

由于本专栏不是专门讲解机器学习的,因此我想该专栏的读者在机器学习模型的实践和理论上是比较薄弱的。 我想大家在经历过数学建模比赛,一定发现机器学习的模型是一定会出现的。无论是哪一场数学建模比赛,一定有一个题是用机器学习的。虽然前面的文章中,讲解了几篇机器学习…

JS实现二叉排搜索树

二叉树中的节点最多只能有两个子节点&#xff1a;一个是左侧子节点&#xff0c;另一个是右侧子节点。而二叉搜索树又可以简称BST&#xff0c;它是二叉树的一种&#xff0c;但是只允许你在左侧节点存储&#xff08;比父节点&#xff09;小的值&#xff0c;在右侧节点存储&#x…

FX粒子(Niagara系统)、顶点法线材质函数、材质参数集——雪和简单地形材质积雪效果

雪 一、利用FX——Niagara系统创建粒子&#xff0c;模板选择 喷泉粒子模板 二、删除不需要的模块 球体位置发射、初始的向上速度、拖拽等和雪无关的模块删除。 三、添加需要的模块并设置 需要大范围降雪故用box location&#xff08;5000,5000,2000&#xff09;&#xff0c;…

Pycharm中使用远程JupyterLab以及JupyterHub登录问题

文章目录需求分析登录网页JupyterHubPycharm配置远程JupyterHub一点思考需求分析 在之前的文章中我们讨论了如何使用Pycharm连接远程服务器并进行调试&#xff0c;Pycharm中SSH、SFTP连接远程服务器编辑调试全面手把手教程&#xff0c;成功在Pycharm中添加了远程Python解释器&…

docker 实战命令集合

目录 docker 基本命令 查看docker的信息 查看docker的版本 docker镜像管理命令 查找镜像 拉取镜像 查看本地仓库的镜像 查看镜像的详细信息 删除本地仓库的镜像 将镜像文件打包 读取打包过后的镜像文件 登入docker hub 推送镜像到dockerHub docker容器管理命令 创…

Keras深度学习入门篇

Keras深度学习入门篇 第一部分&#xff1a;机器学习基础 一、机器学习的四个分支 监督学习 分类回归序列生成&#xff0c;给定一张图像&#xff0c;预测描述图像的文字语法树预测&#xff0c;给定一个句子&#xff0c;预测其分解生成的语法树目标检测&#xff0c;给定一张图…

CTFShow re3

先查一下&#xff0c;没包&#xff0c;64位 IDA看伪代码 再看循环 可以测出i5时v16为e560 而想让v160xffff&#xff0c;只需要ffff-e560就能得到v17[6] 1a9f 所以flag就是1a9f&#xff01;&#xff01; 等下为什么啊我没懂啊 回到前面 v19既没有赋值也没有输入&#xff0…

使用 Qt for Android 获取并利用手机传感器数据(1)开发环境省心搭建

现代手机拥有许多传感器&#xff0c;包括地磁、姿态、GPS、光照、温度、气压、摄像、声音、电磁等&#xff0c;完全就是一个高度集成的科学仪器。不夸张的说&#xff0c;一部手机加上一个外围的计算机和控制系统&#xff0c;做一个功能较强的自主移动机器人并不是不可能。但是&…

【wpf】 当用了数据模板之后如何获取控件的Item?

背景 我对一个treeview使用了数据模板 <TreeView.ItemTemplate> <!--子项的绑定--><HierarchicalDataTemplate DataType"{x:Type local_md:ToolsNodeItem}" ItemsSource"{Binding PathChildren}"><StackPanel Orie…

史上最全的Python包管理工具:Anaconda教程

事实上Anaconda 和 Jupyter notebook已成为数据分析的标准环境。 简单来说&#xff0c;Anaconda是包管理器和环境管理器&#xff0c;Jupyter notebook 可以将数据分析的代码、图像和文档全部组合到一个web文档中。 接下来我详细介绍下Anaconda&#xff0c;并在最后给出Jupyte…

[oeasy]python0022_框架标题的制作_banner_结尾字符串_end

结尾字符串(end) 回忆上次内容 ​python3​​ 的程序是一个 5.3M 的可执行文件 ​​python3​​ 里面存的是 cpu 指令可以执行的那种我们可以把指令对应的汇编找到 ​​objdump -d ~/python3 > python3.asm​​ 汇编语句是和当前机器架构的指令集相关的 ​​uname -a​​可…

【文件I/O】标准IO:库函数

标准IO&#xff1a;库函数一、基本概念1.文件类型2.标准I/O介绍3.流的概念4.文本流和二进制流5.流的缓冲类型6.标准I/O流&#xff08;stdin、stdout、stderr&#xff09;二、标准I/O函数1.fopen、fclose、errrno、strerror、perror&#xff08;打开、关闭文件&#xff0c;输出错…

[附源码]计算机毕业设计SpringBoot四川景区管理系统

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM mybatis Maven Vue 等等组成&#xff0c;B/S模式 M…

SpringBoot实用开发之热部署

目录 热部署 手动启动热部署 自动启动热部署 热部署范围布置 关闭热部署 热部署 能学到spring boot实用开发篇的相信都已经对IDEA和maven了如指掌了&#xff0c;我就基于这些前置知识来说一下热部署&#xff0c;其实也很简单。 手动启动热部署 首先可以在你的pom.xml文…