Python 爬虫入门之爬取妹子图

来源:李英杰  链接:

https://segmentfault.com/a/1190000015798452

听说你写代码没动力?本文就给你动力,爬取妹子图。如果这也没动力那就没救了。

GitHub 地址:

https://github.com/injetlee/Python/blob/master/%E7%88%AC%E8%99%AB%E9%9B%86%E5%90%88/meizitu.py

爬虫成果

当你运行代码后,文件夹就会越来越多,如果爬完的话会有2000多个文件夹,20000多张图片。不过会很耗时间,可以在最后的代码设置爬取页码范围。

本文目标

1. 熟悉 Requests 库,Beautiful Soup 库

2. 熟悉多线程爬取

3. 送福利,妹子图

网站结构

我们从 http://meizitu.com/a/more_1.html 这个链接进去,界面如图一所示

图一

可以看到是一组一组的套图,点击任何一组图片会进入到详情界面,如图二所示

图二

可以看到图片是依次排开的,一般会有十张左右的图片。

实现思路

看了界面的结构,那么我们的思路就有了。

1. 构造 url 链接,去请求图一所示的套图列表界面,拿到每一个页面中的套图列表。

2. 分别进入每个套图中去,下载相应的图片。

代码说明

1. 下载界面的函数,利用 Requests 很方便实现。

def download_page(url):
  '''
  用于下载页面
  '''
  headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0"}
  r = requests.get(url, headers=headers)
  r.encoding = 'gb2312'
  return r.text

2. 获取图一所示的所有套图列表,函数中 link 表示套图的链接,text表示套图的名字

def get_pic_list(html):
  '''
  获取每个页面的套图列表,之后循环调用get_pic函数获取图片
  '''
  soup = BeautifulSoup(html, 'html.parser')
  pic_list = soup.find_all('li', class_='wp-item')
  for i in pic_list:
      a_tag = i.find('h3', class_='tit').find('a')
      link = a_tag.get('href')  # 套图链接
      text = a_tag.get_text()   # 套图名字
      get_pic(link, text)

3. 传入上一步中获取到的套图链接及套图名字,获取每组套图里面的图片,并保存,我在代码中注释了。

def get_pic(link, text):
  '''
  获取当前页面的图片,并保存
  '''
  html = download_page(link)  # 下载界面
  soup = BeautifulSoup(html, 'html.parser')
  pic_list = soup.find('div', id="picture").find_all('img')  # 找到界面所有图片
  headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0"}
  create_dir('pic/{}'.format(text))
  for i in pic_list:
      pic_link = i.get('src')  # 拿到图片的具体 url
      r = requests.get(pic_link, headers=headers)  # 下载图片,之后保存到文件
      with open('pic/{}/{}'.format(text, pic_link.split('/')[-1]), 'wb') as f           f.write(r.content)
          time.sleep(1)

完整代码

完整代码如下,包括了创建文件夹,利用多线程爬取,我设置的是5个线程,可以根据自己机器自己来设置一下。

import requests
import os
import time
import threading
from bs4 import BeautifulSoup def download_page(url):
  '''
  用于下载页面
  '''
  headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0"}
  r = requests.get(url, headers=headers)
  r.encoding = 'gb2312'
  return r.text def get_pic_list(html):
  '''
  获取每个页面的套图列表,之后循环调用get_pic函数获取图片
  '''
  soup = BeautifulSoup(html, 'html.parser')
  pic_list = soup.find_all('li', class_='wp-item')
  for i in pic_list:
      a_tag = i.find('h3', class_='tit').find('a')
      link = a_tag.get('href')
      text = a_tag.get_text()
      get_pic(link, text) def get_pic(link, text):
  '''
  获取当前页面的图片,并保存
  '''
  html = download_page(link)  # 下载界面
  soup = BeautifulSoup(html, 'html.parser')
  pic_list = soup.find('div', id="picture").find_all('img')  # 找到界面所有图片
  headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0"}
  create_dir('pic/{}'.format(text))
  for i in pic_list:
      pic_link = i.get('src')  # 拿到图片的具体 url
      r = requests.get(pic_link, headers=headers)  # 下载图片,之后保存到文件
      with with open('pic/{}/{}'.format(text, pic_link.split('/')[-1]), 'wb') as f:
          f.write(r.content)
          time.sleep(1)   # 休息一下,不要给网站太大压力,避免被封 def create_dir(name):
  if not os.path.exists(name):
      os.makedirs(name) def execute(url):
  page_html = download_page(url)
  get_pic_list(page_html) def main():
  create_dir('pic')
  queue = [i for i in range(1, 72)]   # 构造 url 链接 页码。
  threads = []
  while len(queue) > 0:
      for thread in threads:
          if not thread.is_alive():
              threads.remove(thread)
      while len(threads) < 5 and len(queue) > 0:   # 最大线程数设置为 5
          cur_page = queue.pop(0)
          url = 'http://meizitu.com/a/more_{}.html'.format(cur_page)
          thread = threading.Thread(target=execute, args=(url,))
          thread.setDaemon(True)
          thread.start()
          print('{}正在下载{}页'.format(threading.current_thread().name, cur_page))
          threads.append(thread) if __name__ == '__main__':
  main()

好了,之后运行,我们的爬虫就会孜孜不倦的为我们下载漂亮妹子啦。

(完)

Python 爬虫入门之爬取妹子图的更多相关文章

  1. Python 爬虫入门(二)——爬取妹子图

    Python 爬虫入门 听说你写代码没动力?本文就给你动力,爬取妹子图.如果这也没动力那就没救了. GitHub 地址: https://github.com/injetlee/Python/blob ...

  2. Python 爬虫入门(一)——爬取糗百

    爬取糗百内容 GitHub 代码地址https://github.com/injetlee/Python/blob/master/qiubai_crawer.py 微信公众号:[智能制造专栏],欢迎关 ...

  3. python 爬虫入门----案例爬取上海租房图片

    前言 对于一个net开发这爬虫真真的以前没有写过.这段时间学习python爬虫,今天周末无聊写了一段代码爬取上海租房图片,其实很简短就是利用爬虫的第三方库Requests与BeautifulSoup. ...

  4. python 爬虫入门案例----爬取某站上海租房图片

    前言 对于一个net开发这爬虫真真的以前没有写过.这段时间开始学习python爬虫,今天周末无聊写了一段代码爬取上海租房图片,其实很简短就是利用爬虫的第三方库Requests与BeautifulSou ...

  5. Python爬虫入门:爬取豆瓣电影TOP250

    一个很简单的爬虫. 从这里学习的,解释的挺好的:https://xlzd.me/2015/12/16/python-crawler-03 分享写这个代码用到了的学习的链接: BeautifulSoup ...

  6. Python爬虫入门:爬取pixiv

    终于想开始爬自己想爬的网站了.于是就试着爬P站试试手. 我爬的图的目标网址是: http://www.pixiv.net/search.php?word=%E5%9B%9B%E6%9C%88%E3%8 ...

  7. python 爬虫入门1 爬取代理服务器网址

    刚学,只会一点正则,还只能爬1页..以后还会加入测试 #coding:utf-8 import urllib import urllib2 import re #抓取代理服务器地址 Key = 1 u ...

  8. python - 爬虫入门练习 爬取链家网二手房信息

    import requests from bs4 import BeautifulSoup import sqlite3 conn = sqlite3.connect("test.db&qu ...

  9. 【转载】教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神

    原文:教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神 本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http:/ ...

随机推荐

  1. PSP(4.13——4.19)以及周记录

    1.PSP 4.13 15:15 15:30 0 15 站立会议 A Y min 15:30 19:00 65 145 Account A Y min 21:15 23:00 15 90 博客 B Y ...

  2. Java NIO 详解(二)

    异步IO 异步 I/O 是一种没有阻塞地读写数据的方法.通常,在代码进行 read() 调用时,代码会阻塞直至有可供读取的数据.同样, write()调用将会阻塞直至数据能够写入,关于同步的IO请参考 ...

  3. javaee, javaweb和javase的区别以及各自的知识体系

    javaee, javaweb和javase的区别以及各自的知识体系 来源 https://blog.csdn.net/weixin_39297312/article/details/79454642 ...

  4. 【题解】 [SCOI2010]传送带 (三分法)

    题目描述 在一个2维平面上有两条传送带,每一条传送带可以看成是一条线段.两条传送带分别为线段AB和线段CD.lxhgww在AB上的移动速度为P,在CD上的移动速度为Q,在平面上的移动速度R.现在lxh ...

  5. bzoj5月月赛订正

    已完成2/9(要准备中考啊QwQ) T1 考虑对所有数分解质因数,其中因子>sqrt(100000)的因子最多有一个,于是我们可以暴力维护<sqrt(100000)的因子个数的前缀和. 剩 ...

  6. 洛谷 P2178 [NOI2015]品酒大会 解题报告

    P2178 [NOI2015]品酒大会 题目描述 一年一度的"幻影阁夏日品酒大会"隆重开幕了.大会包含品尝和趣味挑战 两个环节,分别向优胜者颁发"首席品酒家"和 ...

  7. 洛谷 P1344 [USACO4.4]追查坏牛奶Pollutant Control 解题报告

    P1344 [USACO4.4]追查坏牛奶Pollutant Control 题目描述 你第一天接手三鹿牛奶公司就发生了一件倒霉的事情:公司不小心发送了一批有三聚氰胺的牛奶.很不幸,你发现这件事的时候 ...

  8. 滥用基于资源约束委派来攻击Active Directory

    0x00 前言 早在2018年3月前,我就开始了一场毫无意义的争论,以证明TrustedToAuthForDelegation属性是无意义的,并且可以在没有该属性的情况下实现“协议转换”.我相信,只要 ...

  9. BZOJ 4720 [Noip2016]换教室

    4720: [Noip2016]换教室 Description 对于刚上大学的牛牛来说,他面临的第一个问题是如何根据实际情况申请合适的课程.在可以选择的课程中,有2n节课程安排在n个时间段上.在第i( ...

  10. Objective-C 中的协议(@protocol)和接口(@interface)的区别

    Objective-C 中的协议(@protocol),依照我的理解,就是C#, Java, Pascal等语言中的接口(Interface).协议本身不实现任何方法,只是声明方法,使用协议的类必须实 ...