Python教程

用Python爬取彼岸图网图片

本文主要是介绍用Python爬取彼岸图网图片,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 用Python爬取彼岸图网图片

*使用了  四个模块
import time
import requests
from lxml import etree
import os

没有的话自行百度安装。

#encoding = utf-8
import time
import requests
from lxml import etree
import os

# http://www.netbian.com/ 爬虫
if __name__ == '__main__':
    filePath = './保存图片'
    if not os.path.exists(filePath):
        os.mkdir(filePath)
    page_next = 'http://www.netbian.com/dongman/index.htm' #第一页
    header = { #UA伪装
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36 Edg/89.0.774.77"
    }
    for _ in range(1,133):
        page_text = requests.get(url=page_next, headers=header)
        page_text.encoding = 'gbk'
        tree = etree.HTML(page_text.text)
        li_list = tree.xpath('//div[@class="list"]//li')
        _next = tree.xpath('//div[@class="page"]/a[@class="prev"]/@href')
        if len(_next) == 1:
            page_next = 'http://www.netbian.com/' + _next[0]
        else:
            page_next = 'http://www.netbian.com/' + _next[1]
        for _ in li_list:
            time.sleep(0.3)
            href = _.xpath('./a/@href')
            if href != []:
                href = href[0]
            else :
                continue
            if href == 'https://pic.netbian.com/': #广告
                continue
            page_url = 'http://www.netbian.com/' + href
            title = _.xpath('./a/img/@alt')[0]
            spanIndex = title.find(' ',0,len(title)) #空格位置
            title = filePath + '/' + title[0:spanIndex] + '.jpg'
            img_page = requests.get(url=page_url, headers=header)
            _tree = etree.HTML(img_page.text)
            img_url = _tree.xpath('//div[@class="pic"]//a/img/@src')[0]
            try:
                img_file = requests.get(img_url, headers=header, stream=True)
                if img_file != None:
                    with open(title, 'wb') as f:
                        f.write(img_file.content)
                        print(title + '下载成功')
            except:
                print('异常咯,不用管')
    print('Over 全部下载完成')

 

这篇关于用Python爬取彼岸图网图片的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!