码迷,mamicode.com
首页 > 编程语言 > 详细

python网络爬虫之爬取图片

时间:2017-12-14 04:15:23      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:gad   gallery   text   item   pytho   根据   进制   enum   blog   

今天使用requests和BeautifulSoup爬取了一些图片,还是很有成就感的,注释可能有误,希望大家多提意见

import requests
from bs4 import BeautifulSoup
circle = requests.get(‘http://travel.quanjing.com/tag/12975/%E9%A9%AC%E5%B0%94%E4%BB%A3%E5%A4%AB‘)

# 将获取的图片地址依次放入count中
count = []
# 将获取的网页内容放入BeautifulSoup
soup = BeautifulSoup(circle.text, ‘lxml‘)
# 根据谷歌SelectGadGet这个插件,获取html标签,比如获取:#gallery-list
for item in soup.select(‘#gallery-list‘):
    # 用bs4中的find_all获取 #gallery-list 中是否存在 img这个标签
    for img in item.find_all(‘img‘):
        print(‘img‘, img)
        # m 是 img标签中存在的属性
        img_path = img.get(‘m‘)
        count.append(img_path)
# 用enumerate依次取出count中的图片地址 放入v中
for i,v in enumerate(count):
    # 将获取的v值再次放入request中进行与网站相应
    image = requests.get(v)
    # 存取图片过程中,出现不能存储 int 类型,故而,我们对他进行类型转换 str()。w:读写方式打开,b:二进制进行读写。图片一般用到的都是二进制。
    with open(‘D:\\img‘+str(i)+‘.jpg‘, ‘wb‘) as file:
        # content:图片转换成二进制,进行保存。
        file.write(image.content)
    print(i)

 

python网络爬虫之爬取图片

标签:gad   gallery   text   item   pytho   根据   进制   enum   blog   

原文地址:http://www.cnblogs.com/peixu/p/8035060.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!