python之pyquery爬取网站图片并存储到MongoDB

版权声明:为NH4L所有,转载请注明 https://blog.csdn.net/LeeGe666/article/details/81546055

这次爬取图片的示例网站是:斗图吧http://www.doutula.com/photo/list/
用到的包是:pyquery,并非正则及其他的包,因为比较操作简单,易懂。

首先就是得到该网址源代码:特别需要注意,如果没有user-agent,就是这个代理的话,很可能爬取到的就是 403,而不是200,就不能正常,这里还加了一个异常处理,免得报错。

def get_html(url):
    way = {"user-agent": "Mizilla/5.0"}
    try:
        response = requests.get(url,headers=way)
        html = response.text
        return html
    except RequestException:
        print('请求图片出错!!')
        return None

接下来就是分析网页结构了,看图:
这里写图片描述
在看代码:我们用pyquery一步一步来分析,每一个图片他的class都为:col-xs-6
用doc函数分析到我们需要的每一个图片,就是分析到col-xs-6这里,之后再用一个gif字典,分别找到图片的网页代码,和图片的名字,需要用到find().最下面的是下载图片和存储到数据库**

def get_gifImg(html):
    doc = pq(html)
    items = doc('.col-sm-9 .random_picture .list-group .list-group-item .page-content .col-xs-6').items()
    for item in items:
        gif = {
            'img' : item.find('.image_dta').attr('data-original'),
            'name' : item.find('.img-responsive').attr('alt')
        }
        download_image(gif['img'],gif['name'])
        save_to_mongodb(gif)

现在下载图片:file_path为下载的路径,需要一个urllib的包

def download_image(content,name):
    file_path = 'D:\\python Projects\\pyDownloadPictrues\\18-8-9\\{}.gif'.format(name)
    if not os.path.exists(file_path):
        print('正在下载:', name,content)
        urllib.request.urlretrieve(content,file_path)

存储到mongodb:当然需要引入pymongo包

mongoclient = pymongo.MongoClient("localhost",port=27017,connect = False)
db = mongoclient .AugFour
classname = db.doutu
def save_to_mongodb(result):
    try:
        if classname.insert(result):
            print('存储到MongoDB成功', result)
    except Exception:
        print('存储到MongoDB错误', result)

下面贴出所有代码:注意主函数里的循环函数就是从1到10也图片都爬取下来,如果你想要更多,1到100都可以。

import requests
from pyquery import PyQuery as pq
from requests import RequestException
import os
import urllib
import pymongo

mongoclient = pymongo.MongoClient("localhost",port=27017,connect = False)
db = mongoclient .AugFour
classname = db.doutu

def get_html(url):
    way = {"user-agent": "Mizilla/5.0"}
    try:
        response = requests.get(url,headers=way)
        html = response.text
        return html
    except RequestException:
        print('请求图片出错!!')
        return None

def get_gifImg(html):
    doc = pq(html)
    items = doc('.col-sm-9 .random_picture .list-group .list-group-item .page-content .col-xs-6').items()
    for item in items:
        gif = {
            'img' : item.find('.image_dta').attr('data-original'),
            'name' : item.find('.img-responsive').attr('alt')
        }
        download_image(gif['img'],gif['name'])
        save_to_mongodb(gif)

def download_image(content,name):
    file_path = 'D:\\python Projects\\pyDownloadPictrues\\18-8-9\\{}.gif'.format(name)
    if not os.path.exists(file_path):
        print('正在下载:', name,content)
        urllib.request.urlretrieve(content,file_path)


def save_to_mongodb(result):
    try:
        if classname.insert(result):
            print('存储到MongoDB成功', result)
    except Exception:
        print('存储到MongoDB错误', result)

def main():
    for page in range(1,10):
        url = 'http://www.doutula.com/photo/list/?page={}'.format(page)
        html = get_html(url)
        get_gifImg(html)



if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/LeeGe666/article/details/81546055
今日推荐