欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實(shí)現(xiàn)爬取圖書封面

 更新時(shí)間:2018年07月05日 11:44:48   作者:萌妹子哦哦  
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)爬取圖書封面的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了python實(shí)現(xiàn)爬取圖書封面的具體代碼,供大家參考,具體內(nèi)容如下

kongfuzi.py

利用更換代理ip,延遲提交數(shù)據(jù),設(shè)置請(qǐng)求頭破解網(wǎng)站的反爬蟲機(jī)制

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("正在請(qǐng)求%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("當(dāng)前代理%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):
  # 圖書價(jià)格列表
  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)
 
  # 商家地區(qū)列表
  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("沒有找到當(dāng)前節(jié)點(diǎn)下圖片")
  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("/")
      # 只保留最后一個(gè)元素
      fileName = str(i) + "-" + os.path.basename(split[len(split) - 1])
      print("文件名:" + fileName)
      # 建立一個(gè)新路徑
      filePath = os.path.join(dirName, fileName)
      filePathList.append(filePath)
      if not os.path.exists(filePath):
        imageUrlPath = requests.get(downloadUrl)
        # 檢查當(dāng)前網(wǎng)絡(luò)是否請(qǐng)求成功
        imageUrlPath.raise_for_status()
        # 'wb'二進(jìn)制模式打開img適用
        imageFile = open(filePath, 'wb')
        for image in imageUrlPath.iter_content(10000):
          # 把每次遍歷的文件圖像都存儲(chǔ)進(jìn)文件夾中
          imageFile.write(image)
        # 關(guān)閉文件
        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("孔網(wǎng)圖片爬取")
 
  # 處理圖片,轉(zhuǎn)換成可以顯示
  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)) # 創(chuàng)建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="價(jià)格:" + price[i] + "元", bg="#FFF8DC", justify=LEFT)
    infoLabel2.grid(row=rownum * 5 + 2, column=columnnum, padx=45, pady=2, sticky=W)
    infoLabel3 = Label(frame, text="發(fā)貨地區(qū):" + 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) # 豎直滾動(dòng)條
  vbar.place(x=1680, width=20, height=800)
  vbar.configure(command=canvas.yview)
  canvas.config(yscrollcommand=vbar.set) # 設(shè)置
  canvas.create_window((800, 2000), window=frame)
 
  mainloop()
 
 
if __name__ == '__main__':
  # 界面
  root = Tk()
  root.title("孔網(wǎng)圖片爬取")
  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="關(guān)鍵字", 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()

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • python判斷字符串是否純數(shù)字的方法

    python判斷字符串是否純數(shù)字的方法

    這篇文章主要介紹了python判斷字符串是否純數(shù)字的方法,通過isdigit方法進(jìn)行判斷,并給出了改進(jìn)的實(shí)例及采用正則判斷的用法,具有一定的借鑒價(jià)值,需要的朋友可以參考下
    2014-11-11
  • Python數(shù)據(jù)分析之Matplotlib數(shù)據(jù)可視化

    Python數(shù)據(jù)分析之Matplotlib數(shù)據(jù)可視化

    這篇文章主要介紹了Python數(shù)據(jù)分析之Matplotlib數(shù)據(jù)可視化,Matplotlib?是?Python?中常用的?2D?繪圖庫(kù),它能輕松地將數(shù)據(jù)進(jìn)行可視化,作出精美的圖表
    2022-08-08
  • python基礎(chǔ)知識(shí)之索引與切片詳解

    python基礎(chǔ)知識(shí)之索引與切片詳解

    在python的學(xué)習(xí)過程,有些同學(xué)對(duì)索引和切換會(huì)感到困惑,今天我們就來弄清楚它,下面這篇文章主要給大家介紹了關(guān)于python基礎(chǔ)知識(shí)之索引與切片的相關(guān)資料,需要的朋友可以參考下
    2022-05-05
  • python安裝pytorch方式

    python安裝pytorch方式

    這篇文章主要介紹了python安裝pytorch方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • Python?二分查找之bisect庫(kù)的使用詳解

    Python?二分查找之bisect庫(kù)的使用詳解

    。二分查找是一種在有序列表中查找某一特定元素的搜索算法,bisect?庫(kù)是?Python?標(biāo)準(zhǔn)庫(kù)中的一部分,它提供了二分查找的功能,這篇文章主要介紹了Python?二分查找之bisect庫(kù)的使用,需要的朋友可以參考下
    2023-03-03
  • python填充彩色圖形的實(shí)現(xiàn)示例

    python填充彩色圖形的實(shí)現(xiàn)示例

    本文主要介紹了python填充彩色圖形的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • python3 實(shí)現(xiàn)的人人影視網(wǎng)站自動(dòng)簽到

    python3 實(shí)現(xiàn)的人人影視網(wǎng)站自動(dòng)簽到

    這里給大家分享的是使用Python3結(jié)合計(jì)劃任務(wù),實(shí)現(xiàn)的人人影視網(wǎng)站自動(dòng)簽到功能的代碼,非常的實(shí)用,有需要的小伙伴可以參考下
    2016-06-06
  • Python機(jī)器學(xué)習(xí)之AdaBoost算法

    Python機(jī)器學(xué)習(xí)之AdaBoost算法

    今天帶大家來學(xué)習(xí)Python機(jī)器學(xué)習(xí),文中對(duì)AdaBoost算法介紹的很詳細(xì),有非常多的代碼示例,對(duì)正在學(xué)習(xí)python的小伙伴們有很好地幫助,需要的朋友可以參考下
    2021-05-05
  • 詳解python3中zipfile模塊用法

    詳解python3中zipfile模塊用法

    本篇文章給大家分享了關(guān)于python3中zipfile模塊的詳細(xì)用法以及技術(shù)難點(diǎn)解析,有興趣的朋友跟著學(xué)習(xí)下吧。
    2018-06-06
  • Python入門教程(二十八)Python中的JSON

    Python入門教程(二十八)Python中的JSON

    這篇文章主要介紹了Python入門教程(二十八)Python中的JSON,JSON 是用 JavaScript 對(duì)象表示法(JavaScript object notation)編寫的文本,接下來我們就來學(xué)習(xí)一下
    2023-04-04

最新評(píng)論