鱼C论坛

 找回密码
 立即注册
查看: 8455|回复: 43

[技术交流] 爬取彼岸图网4K原图

[复制链接]
发表于 2020-4-16 11:11:14 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 千公子 于 2020-4-16 11:13 编辑
  1. import json
  2. import os
  3. import random
  4. import sys
  5. from concurrent.futures.thread import ThreadPoolExecutor
  6. import pymysql
  7. from lxml import etree
  8. from requests import *
  9. from selenium import webdriver
  10. from selenium.webdriver.common.by import By
  11. from selenium.webdriver.support.ui import WebDriverWait
  12. from selenium.webdriver.support import expected_conditions as EC
  13. from selenium.webdriver.chrome.options import Options

  14. class Spider:
  15.     def __init__(self, cookieFile=None):
  16.         if cookieFile is None:
  17.             self.writeCookie()
  18.             self.cookies = self.readCookies("cookie.txt")
  19.         else:
  20.             self.cookies = self.readCookies(cookieFile)

  21.         self.headers = {
  22.             'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'
  23.         }
  24.         self.indexUrl = "http://pic.netbian.com"
  25.         self.catelogue = self.getCatalogue()
  26.         # 每天限量只能下载200张
  27.         self.downCount = 0
  28.         self.ddir = 'D:\\Data\\照片\\彼岸图网\\'

  29.     def writeCookie(self):
  30.         try:
  31.             chrome_options = Options()
  32.             chrome_options.add_argument('--headless')
  33.             chrome = webdriver.Chrome(options=chrome_options)
  34.             chrome.get("http://pic.netbian.com/e/memberconnect/?apptype=qq")
  35.             ptlogin_iframe = WebDriverWait(chrome, 15).until(EC.presence_of_element_located((By.ID,"ptlogin_iframe")))
  36.             chrome.switch_to.frame(ptlogin_iframe)
  37.             chrome.find_element_by_id("switcher_plogin").click()
  38.             # 设置qq号
  39.             chrome.find_element_by_id("u").send_keys("输入您的QQ号")
  40.             # 设置qq密码
  41.             chrome.find_element_by_id("p").send_keys("输入您的密码")
  42.             # 确定登录
  43.             chrome.find_element_by_id("login_button").click()
  44.             WebDriverWait(chrome, 15).until(EC.url_to_be("http://pic.netbian.com/"))
  45.             with open("cookie.txt", "wt") as f:
  46.                 for cookieMap in chrome.get_cookies():
  47.                     k = cookieMap["name"]
  48.                     v = cookieMap["value"]
  49.                     f.write(k+"="+v+"\n")
  50.         finally:
  51.             chrome.quit()

  52.     def readCookies(self, cookieFile):
  53.         cookies = {}
  54.         with open(cookieFile, "r", encoding="utf-8") as f:
  55.             while True:
  56.                 c = f.readline()
  57.                 if c is not None:
  58.                     c = c.strip()
  59.                     if len(c) == 0:
  60.                         break
  61.                     else:
  62.                         c = c.split("=")
  63.                         cookies[c[0]] = c[1]
  64.                 else:
  65.                     break
  66.         return cookies

  67.     def reqGet(self, url):
  68.         html = get(url, headers=self.headers, cookies=self.cookies).content.decode("gbk")
  69.         return html

  70.     def getImg(self, url):
  71.         return get(url, headers=self.headers, cookies=self.cookies)

  72.     def getCatalogue(self):
  73.         index = self.reqGet(self.indexUrl)
  74.         h = etree.HTML(index)
  75.         href = h.xpath('//div[@class="classify clearfix"]/a/@href')
  76.         title = h.xpath('//div[@class="classify clearfix"]/a/text()')
  77.         return zip(title, href)

  78.     def getRealUrl(self, href):
  79.         """
  80.         ('阿尔卑斯山风景4k高清壁纸3840x2160', 'http://pic.netbian.com/downpic.php?id=21953&classid=53')
  81.         """
  82.         dh = self.reqGet(self.indexUrl + href)
  83.         h = etree.HTML(dh)
  84.         dataId = h.xpath('//div[@class="downpic"]/a/@data-id')[0]
  85.         title = h.xpath('//div[@class="photo-hd"]/h1/text()')[0]
  86.         url = "{0}/e/extend/downpic.php?id={1}&t={2}".format(self.indexUrl, dataId, random.random())
  87.         msg = self.reqGet(url)
  88.         return title, self.indexUrl + json.loads(msg)['pic']

  89.     def getPicUrls(self, url=None, html=None):
  90.         if html is None:
  91.             html = self.reqGet(url)
  92.         h = etree.HTML(html)
  93.         hrefs = h.xpath('//ul[@class="clearfix"]/li/a/@href')
  94.         realHrefs = []
  95.         for href in hrefs:
  96.             realHrefs.append(self.getRealUrl(href))
  97.         return realHrefs

  98.     def getMaxPage(self, html):
  99.         h = etree.HTML(html)
  100.         pages = h.xpath('//div[@class="page"]/a/text()')
  101.         return int(pages[-2].strip())

  102.     def saveToDB(self, category, v, i):
  103.         url = "%s%sindex_%d.html" % (self.indexUrl, v, i)
  104.         if i == 1:
  105.             url = "%s%sindex.html" % (self.indexUrl, v)
  106.         nus = self.getPicUrls(url=url)
  107.         for nu in nus:
  108.             self.add(category, nu[0], nu[1])

  109.     def savePicInfoToDB(self):
  110.         executor = ThreadPoolExecutor(max_workers=64)
  111.         for c, v in self.catelogue:
  112.             html = self.reqGet(self.indexUrl + v)
  113.             if not os.path.exists("%s%s" % (self.ddir, c)):
  114.                 os.mkdir("%s%s" % (self.ddir, c))
  115.             print("%s%s" % (self.ddir, c))
  116.             maxPage = self.getMaxPage(html)
  117.             for i in range(1, maxPage + 1):
  118.                 executor.submit(self.saveToDB, c, v, i)
  119.         executor.shutdown(wait=True)

  120.     def getConn(self):
  121.         conn = pymysql.Connect(
  122.             host="127.0.0.1",
  123.             port=3306,
  124.             charset='utf8',
  125.             user='root',
  126.             password='toor',
  127.             db='photos'
  128.         )
  129.         return conn

  130.     def add(self, category, filename, url):
  131.         try:
  132.             conn = self.getConn()
  133.             cursor = conn.cursor()
  134.             sql = "INSERT INTO purl VALUES ('{0}', '{1}', '{2}')".format(category, filename, url)
  135.             cursor.execute(sql)
  136.             conn.commit()
  137.             print(filename + " was added to database successfully")
  138.         except:
  139.             sys.stderr.write(filename + " was existed!\n")
  140.         finally:
  141.             cursor.close()
  142.             conn.close()

  143.     def downPic(self):
  144.         executor = ThreadPoolExecutor(max_workers=32)
  145.         sql = "select * from purl"
  146.         conn = self.getConn()
  147.         cursor = conn.cursor()
  148.         cursor.execute(sql)
  149.         result = cursor.fetchall()
  150.         for index in range(0, len(result)):
  151.             if self.downCount > 200:
  152.                 print("finished today, welcome come back tomorrow!")
  153.                 break
  154.             executor.submit(self.download, result[index])
  155.         executor.shutdown(wait=True)
  156.         cursor.close()
  157.         conn.close()

  158.     def download(self, cnu):
  159.         path = "{0}{1}\{2}.jpg".format(self.ddir, cnu[0], cnu[1])
  160.         if os.path.exists(path) and os.path.getsize(path) > 10000:
  161.             return
  162.         print("download... " + path)
  163.         rimg = self.getImg(cnu[2])
  164.         if (rimg.status_code != 200 or len(rimg.content) <= 1024):
  165.             print("invalid img!")
  166.             return
  167.         with open(path, "wb") as f:
  168.             f.write(rimg.content)
  169.             self.downCount += 1
  170.         print(str(self.downCount) + ": finished!!! " + path)

  171.     def start(self, hasUrlData=None):
  172.         if hasUrlData is None:
  173.             self.savePicInfoToDB()
  174.         self.downPic()


  175. if __name__ == '__main__':
  176.     spider = Spider() # 如果没有cookie
  177.     # spider = Spider(cookieFile="D:") # 如果有cookie
  178.     spider.start(hasUrlData=True) # 已有数据库文件,直接下载,没有数据库文件则不填
复制代码


  1. SET NAMES utf8mb4;
  2. SET FOREIGN_KEY_CHECKS = 0;

  3. -- ----------------------------
  4. -- Table structure for purl
  5. -- ----------------------------
  6. DROP TABLE IF EXISTS `purl`;
  7. CREATE TABLE `purl`  (
  8.   `category` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  9.   `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  10.   `url` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  11.   PRIMARY KEY (`url`) USING BTREE
  12. ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

  13. SET FOREIGN_KEY_CHECKS = 1;
复制代码




                               
登录/注册后可看大图

记得替换自己的qq号和qq密码,以及sql账号密码

https://blog.csdn.net/qq_38203808/article/details/105483673

csdn上介绍的详细些,哪儿没看懂请回复,我也是初学者,大家一起学习,一起进步!


senjougahara hitagi 战场原黑仪 4K壁纸.jpg

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-4-16 11:13:12 | 显示全部楼层

回帖奖励 +10 鱼币

我去
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-4-16 11:13:31 | 显示全部楼层
高产啊
学的很不错
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-16 11:13:42 | 显示全部楼层
厉害
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-4-16 11:15:37 | 显示全部楼层

回帖奖励 +10 鱼币

已收录入【作品分享与欣赏】!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-16 11:30:58 | 显示全部楼层

回帖奖励 +10 鱼币

那个口算和这个都不错!!!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-16 12:35:40 | 显示全部楼层

回帖奖励 +10 鱼币

不错
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-4-16 19:04:04 | 显示全部楼层
不错哦 nice
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-16 19:07:52 | 显示全部楼层
不错
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-4-16 19:08:24 | 显示全部楼层
不过鱼币还是要拿的
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-16 19:09:16 | 显示全部楼层

回帖奖励 +10 鱼币

老非酋了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-16 19:18:47 | 显示全部楼层

回帖奖励 +10 鱼币

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-4-16 19:34:54 | 显示全部楼层

回帖奖励 +10 鱼币

慢慢来最快
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-16 19:55:12 | 显示全部楼层
这么长。。。。。。。。。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-16 19:55:36 | 显示全部楼层

回帖奖励 +10 鱼币

我去  牛批    代码&鱼币都牛批
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-16 19:59:07 | 显示全部楼层

回帖奖励 +10 鱼币

头晕眼花。。。。。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-16 19:59:28 | 显示全部楼层

回帖奖励 +10 鱼币

看看
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-4-16 20:01:39 | 显示全部楼层
真心看不懂,太长了都没有看到底就头晕了。。。。厉害啊大佬们
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-16 21:39:57 | 显示全部楼层
太长了都没有看到底就头晕了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-16 21:46:21 | 显示全部楼层
学习
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 22:12

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表