Giter Club home page Giter Club logo

jiandan's Introduction

Python爬虫煎蛋网妹子图片

本代码文章首发于公众号「Python知识圈」,如需转载,请通过公众号联系作者pk哥,谢谢

公众号

公众号里提供了我的微信,可以联系到我。

“ 阅读文本大概需要 4.5 分钟。

很多朋友都反应学 python 语言太枯燥,学不进去,其实学语言最好的方法是自己用所学的语言做项目,在项目中学习语言的用法。今天给大家带来的项目是用 python3 爬取煎蛋网妹子的图片。图片质量还不错,我放两张图片大家感受下。

mz1


mz2

这个项目用了 requests + selenium + beautifulsoup 库对网站的图片进行抓取。接下来我就,给大家一步步解析一下,怎么用 python 爬虫爬取图片并下载的。

爬取结果

以上就是爬取的结果,通过运行 meizi.py 代码,就可以把图片保存在我指定的目录下,如果没有此目录,就用程序自动创建目录,爬取的所有图片都保存在此目录下。

程序构造

程序主要是由 6 个函数组成:

  • get_html() :利用 webdriver 来请求对应的网站。

  • get_page():解析面跳转地址。

  • mkdir():判断目录是否存在,不存在就创建一个。

  • get_pic():提取图片链接。

  • download():通过图片链接下载保存。

  • main():程序执行的主函数。

程序思路

对目标网站链接进行分析,找出目标网站链接的规律。

从目标网站里面提取图片链接。

将图片下载并保存在目录中。

源代码分析

我们通过f12调试页面,看到图片的链接,发现此链接并没有在源代码中,我们推测,图片应该是通过 js 加载的,对于需要 js 才能加载出来的网站,我们就可以利用 selenium 的自动化测试请求库来进行加载。利用 selenium 请求可以模拟真实浏览器访问。

利用 selenium 请求网页需要下载 chrome 驱动放在 python 安装目录下。

分页链接分析

原始链接 base_url = 'http://jandan.net/ooxx/',当我们点击下一页时,发现在原始链接的后面加了一段「page-52#comments」。 其中加的数字,就是表示现在所在的页数,通过 BeautifulSoup 库对页面进行解析,用选择器提取表示页数的字段「current-comment-page」,加入到原始链接中进行拼接。

创建目录

用 os.path.exists 方法来个判断,如果不存在此目录就创建一个,如果存在就忽略。

提取图片

用 BeautifulSoup 解析源码,用选择器循环提取图片的链接,并调用 download() 函数下载图片直至下载所有图片。

优化改进

关注公众号「Python知识圈」,在公众号回复「jiandan」也可以获取源码。

本次的程序还有一些不足的地方,比如利用 selenium 库在爬取的时候非常的慢,每页我还设置了 3 秒等待时间,这部分待优化。还有所有页面的图片都保存在一个目录下,没有分开保存,这部分也可以优化。

大家注意身体!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.