python实现爬取图书封面


Posted in Python onJuly 05, 2018

本文实例为大家分享了python实现爬取图书封面的具体代码,供大家参考,具体内容如下

kongfuzi.py

利用更换代理ip,延迟提交数据,设置请求头破解网站的反爬虫机制

import requests
import random
import time
 
 
class DownLoad():
  def __init__(self):
    self.ip_list = ['191.33.179.242:8080', '122.72.108.53:80', '93.190.142.214:80', '189.8.88.125:65301',
            '36.66.55.181:8080', '170.84.102.5:8080', '177.200.72.214:20183', '115.229.115.190:9000']
 
    self.user_agent_list = [
      'User-Agent:Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
      'User-Agent:Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
      'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'
    ]
 
  def get(self, url, proxy=None, timeout=20, num=5):
    print("正在请求%s" % url)
    UA = random.choice(self.user_agent_list)
    headers = {'User-Agent': UA}
 
    if proxy == None:
      try:
        return requests.get(url, headers=headers, timeout=timeout)
      except:
        if num > 0:
          time.sleep(10)
          return self.get(url, num=num - 1)
        else:
          time.sleep(10)
          IP = ''.join(random.choice(self.ip_list).strip())
          proxy = {'http': IP}
          return self.get(url, proxy=proxy, timeout=timeout)
    else:
      try:
        IP = ''.join(random.choice(self.ip_list).strip())
        proxy = {'http': IP}
        return requests.get(url, headers=headers, proxy=proxy, timeout=timeout)
      except:
        if num > 0:
          time.sleep(10)
          IP = ''.join(random.choice(self.ip_list).strip())
          proxy = {'http': IP}
          print("正在更换代理")
          print("当前代理%s" % proxy)
          return self.get(url, proxy=proxy, num=num - 1)

main.py

将爬取的图片保存到本地,然后展示到界面

import kongfuzi
import os
import requests
import bs4
from tkinter import *
from PIL import Image, ImageTk
 
 
# 下载图片,生成图片地址列表和图书信息列表
def download():
  baseUrl = "http://search.kongfz.com"
  keyword = e1.get()
  url = baseUrl + "/product_result/?select=0&key=" + keyword
  print("下载链接:" + url)
  show(url)
 
 
# bs4处理
def changesoup(html):
  htm = html.content
  html_doc = str(htm, 'utf-8')
  soup = bs4.BeautifulSoup(html_doc, "html.parser")
  return soup
 
 
# 图书信息集合
def bookinfo(soup):
  # 图书价格列表
  price = []
  soupprice = soup.select(".first-info .f_right .bold")
  for i in soupprice:
    price.append(i.string)
 
  # 书店名列表
  storename = []
  soupstorename = soup.select(".text a span")
  for each in soupstorename:
    if each.string == None:
      soupstorename.remove(each)
  for i in soupstorename:
    storename.append(i.string)
 
  # 商家地区列表
  place = []
  soupplace = soup.select(".user-place")
  for i in soupplace:
    place.append(i.string)
 
  # 书名列表
  bookname = []
  bookname1 = soup.select(
    ".search-wrap .search-main .search-main-result .result-content .result-list .item .item-info .title .link")
  # print(len(bookname1))
  # print(bookname1)
  for each in bookname1:
    print(each)
    # a = bs4.BeautifulSoup(each, "html.parser")
    a = each.get_text()
    print(a)
    # type(a)
    # a = bs4.BeautifulSoup(a, "html.parser")
    # b = a.get_text()
    bookname.append(a)
  # print(bookname)
  # print(len(bookname))
 
  return bookname, price, place, storename
 
 
# 保存图片
def imgsave(soup):
  dirName = "image"
  os.makedirs(dirName, exist_ok=True)
  filePathList = []
  imgUrl = soup.select(".search-main-result .result-content .result-list .item .item-img .img-box img")
 
  # print(imgUrl)
  if not imgUrl:
    print("没有找到当前节点下图片")
  else:
    i = 0
    for imageUrls in imgUrl:
      # 找到图片地址 获取它
      downloadUrl = imageUrls.get('src')
      # if downloadUrl == "/searchfront/img/error.jpg":
      #   downloadUrl = "http://book.kongfz.com/img/pc/error.jpg"
      print("打印要下载的图片地址:", downloadUrl)
      #   http://book.kongfz.com/img/pc/error.jpg
      # 分割字符
      split = downloadUrl.split("/")
      # 只保留最后一个元素
      fileName = str(i) + "-" + os.path.basename(split[len(split) - 1])
      print("文件名:" + fileName)
      # 建立一个新路径
      filePath = os.path.join(dirName, fileName)
      filePathList.append(filePath)
      if not os.path.exists(filePath):
        imageUrlPath = requests.get(downloadUrl)
        # 检查当前网络是否请求成功
        imageUrlPath.raise_for_status()
        # 'wb'二进制模式打开img适用
        imageFile = open(filePath, 'wb')
        for image in imageUrlPath.iter_content(10000):
          # 把每次遍历的文件图像都存储进文件夹中
          imageFile.write(image)
        # 关闭文件
        imageFile.close()
      i = i + 1
  return filePathList
 
# 图片展示
def show(url):
  xz = kongfuzi.DownLoad()
  html = xz.get(url)
 
  # 添加代理ip到ip_list
  add_ip = e2.get()
  xz.ip_list.append(add_ip)
 
  soup = changesoup(html)
  bookname, price, place, storename = bookinfo(soup)
  # print(bookname)
  # print(price)
  # print(place)
  # print(storename)
  filePathList = imgsave(soup)
  root1 = Toplevel()
  root1.geometry("1720x800")
  root1.title("孔网图片爬取")
 
  # 处理图片,转换成可以显示
  photo = []
  temp = []
  for each in filePathList:
    temp = Image.open(each)
    photo.append(ImageTk.PhotoImage(temp))
 
  canvas = Canvas(root1, width=1700, height=800, scrollregion=(0, 0, 0, 4000)) # 创建canvas
  canvas.place(x=10, y=10) # 放置canvas的位置
 
  frame = Frame(canvas) # 把frame放在canvas里
  frame.place(width=1680, height=800)
 
  for i in range(50):
    # 图片行列
    rownum = int(i / 5)
    columnnum = i % 5
 
    # photo = ImageTk.PhotoImage(Image.open(filePathList[i]))
    imgLabel1 = Label(frame, image=photo[i], width=280, height=280)
    imgLabel1.grid(row=rownum * 5, column=columnnum, padx=10, pady=5)
 
    infoLabel1 = Label(frame, text="书名:" + bookname[i], bg="#FFF8DC", justify=LEFT)
    infoLabel1.grid(row=rownum * 5 + 1, column=columnnum, padx=45, pady=2, sticky=W)
    infoLabel2 = Label(frame, text="价格:" + price[i] + "元", bg="#FFF8DC", justify=LEFT)
    infoLabel2.grid(row=rownum * 5 + 2, column=columnnum, padx=45, pady=2, sticky=W)
    infoLabel3 = Label(frame, text="发货地区:" + place[i], bg="#FFF8DC", justify=LEFT)
    infoLabel3.grid(row=rownum * 5 + 3, column=columnnum, padx=45, pady=2, sticky=W)
    infoLabel4 = Label(frame, text="书店:" + storename[i], bg="#FFF8DC", justify=LEFT)
    infoLabel4.grid(row=rownum * 5 + 4, column=columnnum, padx=45, pady=2, sticky=W)
 
  vbar = Scrollbar(canvas, orient=VERTICAL) # 竖直滚动条
  vbar.place(x=1680, width=20, height=800)
  vbar.configure(command=canvas.yview)
  canvas.config(yscrollcommand=vbar.set) # 设置
  canvas.create_window((800, 2000), window=frame)
 
  mainloop()
 
 
if __name__ == '__main__':
  # 界面
  root = Tk()
  root.title("孔网图片爬取")
  e1 = Entry(root)
  e2 = Entry(root)
  e1.grid(row=0, column=0, padx=20, pady=20)
  e2.grid(row=0, column=2, padx=20, pady=20)
  label1 = Label(root, text="关键字", width=10).grid(row=0, column=1, padx=10, pady=5)
  label2 = Label(root, text="添加代理ip", width=10).grid(row=0, column=3, padx=10, pady=5)
  btn1 = Button(root, text="搜索", width=10, command=download).grid(row=1, column=1, padx=10, pady=5)
  # print(e1.get())
  mainloop()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
详解Python中open()函数指定文件打开方式的用法
Jun 04 Python
Python进阶_关于命名空间与作用域(详解)
May 29 Python
Python在信息学竞赛中的运用及Python的基本用法(详解)
Aug 15 Python
python解析html提取数据,并生成word文档实例解析
Jan 22 Python
Python如何爬取实时变化的WebSocket数据的方法
Mar 09 Python
简单了解python的内存管理机制
Jul 08 Python
Django+zTree构建组织架构树的方法
Aug 21 Python
python3中关于excel追加写入格式被覆盖问题(实例代码)
Jan 10 Python
Python中的__init__作用是什么
Jun 09 Python
通过实例解析python创建进程常用方法
Jun 19 Python
Python如何优雅删除字符列表空字符及None元素
Jun 25 Python
python如何支持并发方法详解
Jul 25 Python
Python定义二叉树及4种遍历方法实例详解
Jul 05 #Python
Python使用pyodbc访问数据库操作方法详解
Jul 05 #Python
如何优雅地处理Django中的favicon.ico图标详解
Jul 05 #Python
解决pandas中读取中文名称的csv文件报错的问题
Jul 04 #Python
解决Python pandas df 写入excel 出现的问题
Jul 04 #Python
python处理数据,存进hive表的方法
Jul 04 #Python
利用Pandas读取文件路径或文件名称包含中文的csv文件方法
Jul 04 #Python
You might like
一个简单的PHP入门源程序
2006/10/09 PHP
一个用mysql_odbc和php写的serach数据库程序
2006/10/09 PHP
php利用云片网实现短信验证码功能的示例代码
2017/11/18 PHP
PHP将英文数字转换为阿拉伯数字实例讲解
2019/01/28 PHP
JavaScript高级程序设计(第3版)学习笔记11 内建js对象
2012/10/11 Javascript
中止javascript执行的方法
2014/02/14 Javascript
javascript时间函数大全
2014/06/30 Javascript
dreamweaver 8实现Jquery自动提示
2014/12/04 Javascript
jQuery中prevAll()方法用法实例
2015/01/08 Javascript
AngularJS的内置过滤器详解
2015/05/14 Javascript
浅析jquery unbind()方法移除元素绑定的事件
2016/05/24 Javascript
使用JavaScript获取URL中的参数(两种方法)
2016/11/16 Javascript
JavaScript实现图像模糊化的方法实例
2017/01/15 Javascript
Bootstrap 表单验证formValidation 实现远程验证功能
2017/05/17 Javascript
原生JS实现小小的音乐播放器
2017/10/16 Javascript
Node.js中的child_process模块详解
2018/06/08 Javascript
JS实现简单tab选项卡切换
2019/10/25 Javascript
vue.js的简单自动求和计算实例
2019/11/08 Javascript
jquery实现弹窗(系统提示框)效果
2019/12/10 jQuery
用云开发Cloudbase实现小程序多图片内容安全监测的代码详解
2020/06/07 Javascript
vue实现按钮切换图片
2021/01/20 Vue.js
python批量导出导入MySQL用户的方法
2013/11/15 Python
python实现人人网登录示例分享
2014/01/19 Python
浅谈python为什么不需要三目运算符和switch
2016/06/17 Python
python3字符串操作总结
2019/07/24 Python
Python图像处理库PIL的ImageGrab模块介绍详解
2020/02/26 Python
django处理select下拉表单实例(从model到前端到post到form)
2020/03/13 Python
Python插件机制实现详解
2020/05/04 Python
小学生新学期寄语
2014/01/19 职场文书
酒店行政人事部经理职务说明书
2014/02/26 职场文书
事业单位绩效考核实施方案
2014/03/27 职场文书
党员干部群众路线个人整改措施
2014/09/18 职场文书
罗马假日观后感
2015/06/08 职场文书
高中历史教学反思
2016/02/19 职场文书
当你焦虑迷茫时,请读读这6句话
2019/07/24 职场文书
CentOS8.4安装Redis6.2.6的详细过程
2021/11/20 Redis