Python运用urllib2和BeautifulSoup爬取网站ZOL桌面壁纸上的精美电脑壁纸

Python运用urllib2和BeautifulSoup爬取网站ZOL桌面壁纸上的精美电脑壁纸

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/7/28 13:00
# @File    : SpyImg.py

"""
爬取壁纸
"""


from bs4 import BeautifulSoup
import urllib2
import urllib
import re

page_URL=[]  #存放每个待爬取图片的网页的URL
img_URL=[]  #存放图片地址URL


#对传入的URL进行解析,获取下一页面的URL
def paser_Page_URL(url):
    response=urllib2.urlopen(url,timeout=5)
    soup=BeautifulSoup(response)
    html=soup.find_all(id='pageNext')
    i=html[0]
    if i is not None:
        the_url=i.get('href')
        #此处根据网站实际,此时为最后一页壁纸,往后需跳转到下一个图集
        if the_url=='javascript:;':
            return get_Next_Page_URL(url)
        else:
            the_url='http://desk.zol.com.cn'+the_url
            return the_url


#解析页面,获取图片URL
def paser_Img_URl(url):
    response=urllib2.urlopen(url)
    soup=BeautifulSoup(response)
    html=soup.find_all(id='bigImg')
    i=html[0]
    if i is not None:
        img_url=i.get('src')
        return img_url

#根据URL进行对应图片下载
def download_Img(img_url):
    x=0
    for url in img_url:
        urllib.urlretrieve(url,'D:\IMGS\%s.jpg' % x)
        print '下载第 %s 张完成' % x
        x+=1


#获取下一图集
def get_Next_Page_URL(url):
    response=urllib2.urlopen(url)
    soup=BeautifulSoup(response)
    html=soup.select('.txt')
    string=html[1]
    string=str(string)  #需转换成字符串
    linkPattern = re.compile("href=\"(.+?)\"")  #运用正则表达式解析出href里面的内容
    match=re.findall(linkPattern,string)
    the_url=match[0]
    the_url='http://desk.zol.com.cn'+the_url
    return the_url


root_url='http://desk.zol.com.cn/bizhi/7089_87888_2.html' #开始地址
num=0  #num为爬取图片数量
while num<=10:
    url=paser_Page_URL(root_url)
    print url
    if url is not None:
        page_URL.append(url)
        root_url=url
        img_url=paser_Img_URl(url)
        img_URL.append(img_url)
        print '添加',num
        num+=1
    else:
        num+=1


download_Img(img_URL)  #下载图片到本地
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值