博客
关于我
python爬虫beautifulsoup4系列3
阅读量:470 次
发布时间:2019-03-06

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

前言

本篇手把手教大家如何爬取网站上的图片,并保存到本地电脑

 

一、目标网站

1.随便打开一个风景图的网站:http://699pic.com/sousuo-218808-13-1.html

2.用firebug定位,打开firepath里css定位目标图片

3.从下图可以看出,所有的图片都是img标签,class属性都是lazy

 

二、用find_all找出所有的标签

1.find_all(class_="lazy")获取所有的图片对象标签

2.从标签里面提出jpg的url地址和title

1 # coding:utf-8 2 from bs4 import BeautifulSoup 3 import requests 4 import os 5 r = requests.get("http://699pic.com/sousuo-218808-13-1.html") 6 fengjing = r.content 7 soup = BeautifulSoup(fengjing, "html.parser") 8 # 找出所有的标签 9 images = soup.find_all(class_="lazy")10 # print images # 返回list对象11 12 for i in images:13     jpg_rl = i["data-original"]  # 获取url地址14     title = i["title"]           # 返回title名称15     print title16     print jpg_rl17     print ""

 

三、保存图片

1.在当前脚本文件夹下创建一个jpg的子文件夹

2.导入os模块,os.getcwd()这个方法可以获取当前脚本的路径

3.用open打开写入本地电脑的文件路径,命名为:os.getcwd()+"\\jpg\\"+title+'.jpg'(命名重复的话,会被覆盖掉)

4.requests里get打开图片的url地址,content方法返回的是二进制流文件,可以直接写到本地

 

四、参考代码

from bs4 import BeautifulSoupimport requestsimport osr = requests.get("http://699pic.com/sousuo-218808-13-1.html")fengjing = r.contentsoup = BeautifulSoup(fengjing, "html.parser")# 找出所有的标签images = soup.find_all(class_="lazy")# print images # 返回list对象for i in images:    try:        jpg_rl = i["data-original"]        title = i["title"]        print(title)        print(jpg_rl)        print("")        with open(os.getcwd()+"\\jpg\\"+title+'.jpg', "wb") as f:            f.write(requests.get(jpg_rl).content)    except:        pass

 

 

对python接口自动化有兴趣的,可以加python接口自动化QQ群:226296743

也可以关注下我的个人公众号:

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

你可能感兴趣的文章
Mysql 重置自增列的开始序号
查看>>
MySQL 高可用性之keepalived+mysql双主
查看>>
mysql5.6.21重置数据库的root密码
查看>>
MySQL5.6忘记root密码(win平台)
查看>>
mysql5.7 for windows_MySQL 5.7 for Windows 解压缩版配置安装
查看>>
MySQL5.7.18主从复制搭建(一主一从)
查看>>
MySQL5.7.19-win64安装启动
查看>>
mysql5.7性能调优my.ini
查看>>
Mysql5.7深入学习 1.MySQL 5.7 中的新增功能
查看>>
Mysql5.7版本单机版my.cnf配置文件
查看>>
mysql5.7的安装和Navicat的安装
查看>>
mysql5.7示例数据库_Linux MySQL5.7多实例数据库配置
查看>>
MySQL8.0.29启动报错Different lower_case_table_names settings for server (‘0‘) and data dictionary (‘1‘)
查看>>
MySQL8修改密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
查看>>
MySQL8找不到my.ini配置文件以及报sql_mode=only_full_group_by解决方案
查看>>
mysql8的安装与卸载
查看>>
mysqlbinlog报错unknown variable ‘default-character-set=utf8mb4‘
查看>>
mysqldump 导出中文乱码
查看>>
mysqldump备份时忽略某些表
查看>>
mysqldump实现数据备份及灾难恢复
查看>>