前言
本篇手把手教大家如何爬取网站上的图片,并保存到本地电脑
一、目标网站
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
# coding:utf-8 from bs4 import BeautifulSoup import requests import os r = requests.get("http://699pic.com/sousuo-218808-13-1.html") fengjing = r.content soup = BeautifulSoup(fengjing, "html.parser") # 找出所有的标签 images = soup.find_all(class_="lazy") # print images # 返回list对象
for i in images: jpg_rl = i["data-original"] title = i["title"] print title print jpg_rl print ""
三、保存图片
1.在当前脚本文件夹下创建一个jpg的子文件夹
2.导入os模块,os.getcwd()这个方法可以获取当前脚本的路径
3.用open打开写入本地电脑的文件路径,命名为:os.getcwd()+"\\jpg\\"+title+'.jpg'(命名重复的话,会被覆盖掉)
4.requests里get打开图片的url地址,content方法返回的是二进制流文件,可以直接写到本地
四、参考代码 # coding:utf-8 from bs4 import BeautifulSoup import requests import os r = requests.get("http://699pic.com/sousuo-218808-13-1.html") fengjing = r.content soup = BeautifulSoup(fengjing, "html.parser") # 找出所有的标签 images = soup.find_all(class_="lazy") # print images # 返回list对象
for i in images: 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)
python接口自动化QQ群:226296743 《selenium高级自动化》已出书,可以购买正版(点左下角阅读原文)https://yuedu.baidu.com/ebook/0f6a093b7dd184254b35eefdc8d376eeaeaa17e3
|