利用lxml爬取煎蛋妹子所有图片

这个爬虫是单线程,因为在多线程的情况下,请求容易被煎蛋搞掉,而且还要sleep(1)不然速度过快也会被干掉,然而即使是这样也不能全部爬取,当然,我用的headers只有一个useragent,有心的可以多弄几个每次请求都随即取就好了 上代码

import urllib
import urllib2
from lxml import html
import os
import time

def getTree(pageUrl):
    #这里可以用多个useragent随机,比较不容易被干掉
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
    myHeaders = {'User-Agent': user_agent}
    req = urllib2.Request(pageUrl,headers=myHeaders)
    page_content = urllib2.urlopen(req).read()
    tree = html.fromstring(page_content)
    return tree

#获取当前页面的后面页面的URL
def getAllUrls(n_tree):
    url_arr = n_tree.xpath('//div[@class="comments"]/div[@class="cp-pagenavi"]/a/@href')
    return url_arr

#通过图片链接下载图片
def downLoadPic(picUrl,count):
    string = picUrl[-3:]
    if string == 'jpg':
        urllib.urlretrieve(picUrl,'f:\\picFile\\'+str(count)+'.jpg')
        time.sleep(1)
    # else:
        #gif图
        # urllib.urlretrieve(picUrl,'f:\\picFile\\'+str(count)+'.gif')

#获取当前页面的所有图片链接
def getAllPicUrls(m_tree):
    mylist = []
    pic_arr = m_tree.xpath('//div[@class="row"]/div[@class="text"]/p/img/@src')
    for e in pic_arr:
        e = 'http:'+e
        mylist.append(e)            
    return mylist

if __name__ == '__main__':
    mytree = getTree('http://jandan.net/ooxx')
    pic_arr = getAllPicUrls(mytree)
    count = 0 
    os.mkdir('f:\\picFile\\')
    for e in pic_arr:
        count = count+1
        downLoadPic(e,count)
    afterList = getAllUrls(mytree)
    afterPageUrl = afterList[0]
    while afterPageUrl> 0:
        newTree = getTree(afterPageUrl)
        newPicArr = getAllPicUrls(newTree)
        for a in newPicArr:
            count = count + 1
            downLoadPic(a,count)
        newList = getAllUrls(newTree)
        afterPageUrl = newList[2]
        print '------->'+afterPageUrl
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值