博客
关于我
Python爬取堆糖网优美古风头像(附源码)
阅读量:634 次
发布时间:2019-03-14

本文共 1207 字,大约阅读时间需要 4 分钟。

前言

文中文字及图片均来源网络供学习交流使用,版权归原作者,若有问题请联系处理。

若想完成爬虫程序,需先安装以下工具包:

  • requests 网络库
  • bs4 页面选择器

安装步骤:

  • pip install requests
  • pip install bs4

os 是 Python 自带工具库,用于文件操作。

SSL 证书支持:

https 网站基于 SSL 加密传输,需注意证书验证。

一般爬虫流程

1. 模拟浏览器访问目标网站 2. 使用 requests 发起 HTTP 请求获取网页数据 3. 通过 bs4 筛选所需数据 4. 根据规则下载图片

本次目标

爬取堆糖网图片: 目标网站:https://www.duitang.com/

爬虫代码

导入工具: ```pythonimport requestsimport osfrom bs4 import BeautifulSoup```

设置请求头:

headers = {    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'}

证书验证:

import sslssl._create_default_https_context = ssl._create_unverified_context

图片爬取函数:

def get_images(url):    images_html = requests.get(url, headers=headers).text    soup = BeautifulSoup(images_html, 'lxml')    images_list = soup.find_all('div', class_='mbpho')        for image in images_list:        image_data = image.find('a', class_='a')        image_url = image_data.find('img')['src']        image_id = image_data.find('img')['data-rootid']                try:            urllib.request.urlretrieve(image_url, f'./古风头像/{image_id}{os.path.splitext(image_url)[-1]}')            print('下载成功...')        except:            pass

效果图

(以下均为图片链接,已去除外部资源引用)

转载地址:http://cqioz.baihongyu.com/

你可能感兴趣的文章
openSUSE 13.1 Milestone 2 发布
查看>>
openSUSE推出独立 GUI 包管理工具:YQPkg,简化了整个软件包管理流程
查看>>
OpenVP共用账号 一个账号多台电脑登录
查看>>
OpenVSwtich(OVS)Vlan间路由实战 附实验环境
查看>>
Openwrt LuCI模块练习详细步骤
查看>>
openwrt_git_pull命令提示merger冲突时如何解决?
查看>>
OpenWrt包管理软件opkg的使用(极路由)
查看>>
OpenWrt固件编译刷机完全总结
查看>>
Open××× for Linux搭建之二
查看>>
Open×××有线网络时使用正常,无线网络时使用报错的解决方案
查看>>
Opera Mobile Classic Emulator
查看>>
Operation not supported on read-only collection 的解决方法 - [Windows Phone开发技巧系列1]
查看>>
OperationResult
查看>>
Operations Manager 2007 R2系列之仪表板(多)视图
查看>>
operator new and delete
查看>>
operator new 与 operator delete
查看>>
operator() error
查看>>
OPPO K3在哪里打开USB调试模式的完美方法
查看>>
oppo后端16连问
查看>>
OPPO软件商店APP侵权投诉流程
查看>>