Python使用xpath实现图片爬取

作者:lurkerzhang 时间:2023-07-10 16:45:42 

高性能异步爬虫

目的:在爬虫中使用异步实现高性能的数据爬取操作

异步爬虫的方式:

- 多线程、多进程(不建议):

好处:可以为相关阻塞的操作单独开启多线程或进程,阻塞操作就可以异步执行;

弊端:无法无限制的开启多线程或多进程。

- 线程池、进程池(适当的使用):

好处:我们可以降低系统对进程或线程创建和销毁的一个频率,从而很好的降低系统的开销;

弊端:池中线程或进程的数据是有上限的。

代码如下


# _*_ coding:utf-8 _*_
"""
@FileName  :6.4k图片解析爬取(异步高性能测试).py
@CreateTime :2020/8/14 0014 10:01
@Author   : Lurker Zhang
@E-mail   : 289735192@qq.com
@Desc.   :
"""

import requests
from lxml import etree
from setting.config import *
import json
import os
import time
from multiprocessing.dummy import Pool

def main():
 # 图片采集源地址
 # source_url = 'http://pic.netbian.com/4kmeinv/'
 # temp_url = 'http://pic.netbian.com/4kmeinv/index_{}.html'
 # source_url = 'http://pic.netbian.com/4kdongman/'
 # temp_url = 'http://pic.netbian.com/4kdongman/index_{}.html'
 source_url = 'http://pic.netbian.com/4kmingxing/'
 temp_url = 'http://pic.netbian.com/4kmingxing/index_{}.html'
 # 本此采集前多少页,大于1的整数
 page_sum = 136
 all_pic_list_url = []
 if page_sum == 1:
   pic_list_url = source_url
   print('开始下载:' + pic_list_url)
   all_pic_list_url.append(pic_list_url)
 else:
   # 先采集第一页
   pic_list_url = source_url
   # 调用采集单页图片链接的函数
   all_pic_list_url.append(pic_list_url)
   # 再采集第二页开始后面的页数
   for page_num in range(2, page_sum + 1):
     pic_list_url = temp_url.format(page_num)
     all_pic_list_url.append(pic_list_url)
 # 单页图片多线程解析
 pool1 = Pool(10)
 pool1.map(down_pic, all_pic_list_url)

print('采集完成,本地成功下载{0}张图片,失败{1}张图片。'.format(total_success, total_fail))
 # 存储已下载文件名列表:
 with open("../depository/mingxing/pic_name_list.json", 'w', encoding='utf-8') as fp:
   json.dump(pic_name_list, fp)

def down_pic(pic_list_url):
 print("准备解析图片列表页:",pic_list_url)
 # 获取图片列表页的网页数据
 pic_list_page_text = requests.get(url=pic_list_url, headers=headers).text
 tree_1 = etree.HTML(pic_list_page_text)
 # 获取图片地址列表
 pic_show_url_list = tree_1.xpath('//div[@class="slist"]/ul//a/@href')
 pic_url_list = [get_pic_url('http://pic.netbian.com' + pic_show_url) for pic_show_url in pic_show_url_list]

# 开始下载并保存图片(多线程)
 pool2 = Pool(5)
 pool2.map(save_pic, pic_url_list)

def save_pic(pic_url):
 print("准备下载图片:",pic_url)
 global total_success, total_fail, pic_name_list,path
 picname = get_pic_name(pic_url)
 if not picname in pic_name_list:
   # 获取日期作为保存位置文件夹

pic = requests.get(url=pic_url, headers=headers).content
   try:
     with open(path + picname, 'wb') as fp:
       fp.write(pic)
   except IOError:
     print(picname + "保存失败")
     total_fail += 1
   else:
     pic_name_list.append(picname)
     total_success += 1
     print("成功保存图片:{0},共成功采集{1}张。".format(picname, total_success))

else:
   print("跳过,已下载过图片:" + picname)
   total_fail += 1

def get_pic_name(pic_url):
 return pic_url.split('/')[-1]

def get_pic_url(pic_show_url):
 tree = etree.HTML(requests.get(url=pic_show_url, headers=headers).text)
 return 'http://pic.netbian.com/' + tree.xpath('//div[@class="photo-pic"]/a/img/@src')[0]

if __name__ == '__main__':
 # 读入已采集图片的名称库,名称存在重复的表示已经采集过将跳过不采集
 if not os.path.exists('../depository/mingxing/pic_name_list.json'):
   with open("../depository/mingxing/pic_name_list.json", 'w', encoding="utf-8") as fp:
     json.dump([], fp)
 with open("../depository/mingxing/pic_name_list.json", "r", encoding="utf-8") as fp:
   pic_name_list = json.load(fp)
 path = '../depository/mingxing/' + time.strftime('%Y%m%d', time.localtime()) + '/'
 if not os.path.exists(path):
   os.mkdir(path)
 # 记录本次采集图片的数量
 total_success = 0
 total_fail = 0
 main()

来源:https://www.cnblogs.com/lurkerzhang/p/13561095.html

标签:Python,xpath,爬取
0
投稿

猜你喜欢

  • Python Django实现个人博客系统的搭建

    2021-12-17 15:04:58
  • MySQL中的随机抽取的实现

    2024-01-17 21:07:42
  • Sanic框架异常处理与中间件操作实例分析

    2023-04-30 00:27:31
  • django在接受post请求时显示403forbidden实例解析

    2021-12-19 22:41:27
  • 使用Python标准库中的wave模块绘制乐谱的简单教程

    2023-11-20 14:21:35
  • Python+Pygame实现神庙逃亡游戏

    2022-06-12 16:26:28
  • python中封装token问题

    2022-09-29 01:09:32
  • asp无限级分类加js收缩伸展功能代码

    2009-12-08 12:25:00
  • 一文带你了解Golang中的并发性

    2024-04-30 10:00:45
  • ASP分段读取数据库代码

    2009-10-12 12:28:00
  • IE8将是IE的最后一个版本?

    2009-03-12 12:44:00
  • Python之列表的append()方法最容易踩的坑

    2022-05-14 18:56:53
  • Python continue语句用法实例

    2021-02-16 07:40:00
  • python 字段拆分详解

    2021-03-16 22:59:58
  • python 合并表格详解

    2023-09-08 16:03:48
  • 解决用CSS控制DIV居中失效的问题

    2010-04-05 21:53:00
  • python比较两个列表大小的方法

    2023-01-14 22:24:40
  • Python中每次处理一个字符的5种方法

    2023-09-26 02:49:13
  • JS实现跟随鼠标闪烁转动色块的方法

    2024-04-16 09:05:21
  • python可以美化表格数据输出结果的两个工具

    2022-06-05 02:33:32
  • asp之家 网络编程 m.aspxhome.com