scrapy+xpath爬取不可描述网站[通俗易懂]

scrapy+xpath爬取不可描述网站[通俗易懂]今天来爬一个让人很有动力的网站,网址就不便放上来了,看看有没有有缘人能得知了还是先来items.pyimportscrapyclassAvmooItem(scrapy.Item):#definethefieldsforyouritemherelike:#name=scrapy.Field()name=scrapy.Field()

大家好,又见面了,我是你们的朋友全栈君。

今天来爬一个让人很有动力的网站,网址就不便放上来了,看看有没有有缘人能得知了这里写图片描述
还是先来items.py

import scrapy
 class AvmooItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() name=scrapy.Field() birthday=scrapy.Field() age=scrapy.Field() height=scrapy.Field() cup=scrapy.Field() bust=scrapy.Field() waistline=scrapy.Field() hipline=scrapy.Field() birthplace=scrapy.Field() Avatar=scrapy.Field() designations=scrapy.Field() des_imgs=scrapy.Field() des_urls=scrapy.Field()

各位施主从这些字段应该就可以看出来了吧
接下来就是主爬取程序了
spider.py

# -*- coding:utf-8 -*-

import scrapy
from AVMOO.items import AvmooItem
import os
import requests

class AvmooSpider(scrapy.Spider):
    name='AVMOO'
    allowed_domains=['xxx.xx','jp.netcdn.space/digital/video/']#,'xxxx.xx']
    start_urls=['https://xxx.xx/cn/actresses/']
    base_url='https://xxx.xx'
    des_imgs=[]


    def parse(self,response):
        star_urls=response.xpath('//a[@class="avatar-box text-center"]/@href').extract()
        for star_url in star_urls:
            yield scrapy.Request(star_url,callback=self.star_item)
        next_url=self.base_url+response.xpath('//a[@name="nextpage"]/@href').extract()[0]
        if next_url:
            yield scrapy.Request(next_url,callback=self.parse)

    def star_item(self,response):
        item=AvmooItem()
        item['name']=response.xpath('//span[@class="pb-10"]/text()').extract()[0]
        item['age']=response.xpath('//p/text()')[1].extract()
        item['birthday']=response.xpath('//p/text()')[0].extract()
        item['height']=response.xpath('//p/text()')[2].extract()
        item['cup']=response.xpath('//p/text()')[3].extract()
        item['bust']=response.xpath('//p/text()')[4].extract()
        item['waistline']=response.xpath('//p/text()')[5].extract()
        item['hipline']=response.xpath('//p/text()')[6].extract()
        item['birthplace']=response.xpath('//p/text()')[7].extract()
        self.mkdir('/home/shitfly/webspider/AVMOO/avmoo',item['name'])
        f=open(item['name']+'.txt','w+')
        print '写入个人信息'
        self.save_txt(item,f)
        movie_urls=response.xpath('//a[@class="movie-box"]/@href').extract()
        for movie_url in movie_urls:
            yield scrapy.Request(movie_url,meta={
  
  'item1':item},callback=self.movie_item)
        next_url=self.base_url+response.xpath('//a[@name="nextpage"]/@href').extract()[0]
        if next_url:
            yield scrapy.Request(next_url,meta={
  
  'item1':item},callback=self.star_item2)

    def star_item2(self,response):
        item1=response.meta['item1']
        movie_urls=response.xpath('//a[@class="movie-box"]/@href').extract()
        for movie_url in movie_urls:
            yield scrapy.Request(movie_url,meta={
  
  'item1':item1},callback=self.movie_item)
        try:
            next_url=self.base_url+response.xpath('//a[@name="nextpage"]/@href').extract()[0]
        except:
            pass
        if next_url:
            yield scrapy.Request(next_url,meta={
  
  'item1':item1},callback=self.star_item2)

    def movie_item(self,response):
        item=AvmooItem()
        item2=response.meta['item1']
        item['name']=item2['name']
        item['designations']=response.xpath('//span[@style="color:#CC0000;"]/text()').extract()[0]
        base_path='/home/shitfly/webspider/AVMOO/avmoo'+'/'+item['name']
        self.mkdir(base_path,item['designations'])
        cover=response.xpath('//a[@class="bigImage"]/img/@src').extract()[0]
        self.des_imgs=[]
        self.des_imgs.append(cover)
        des_imgs=response.xpath('//a[@class="sample-box"]/div[@class="photo-frame"]/img/@src').extract()
        for des_img in des_imgs:
            s=des_img.split('-')
            s[0]=s[0]+str('jp-')
            des_img=''.join(i for i in s)
            self.des_imgs.append(des_img)
        item['des_imgs']=self.des_imgs
        yield item


    def mkdir(self,base_path,title): #title是文件夹名
        title=title.strip()
        isExists=os.path.exists(os.path.join(base_path,title))
        if not isExists:
            print "新建",title,"文件夹"
            os.makedirs(os.path.join(base_path,title))
            os.chdir(os.path.join(base_path,title))
        else:
            print title,'已存在'
            os.chdir(os.path.join(base_path,title))
        return True

    def save_txt(self,item,f):
        it=[]
        inf=['age','birthday','height','cup','bust','waistline','hipline','birthplace']
        for i in inf:
            it.append(item[i])
        for it_e in it:
            it_e=it_e+'\n'
            f.write(it_e.encode('utf-8'))

网址已被和谐,这里希望图片保存到本地,所以还是在磁盘中建立文本文件和文件夹。想要传递字段的话,使用meta={‘item1’:item},下一个函数接收是item1=response.meta[‘item1’]。

保存图片的话在管道中来进行保存
pipelines.py

import requests

class AvmooPipeline(object):
    def process_item(self, item, spider):
        des_imgs=item['des_imgs']
        path='/home/shitfly/webspider/AVMOO/avmoo'+'/'+item['name']+'/'+item['designations']
        for i in range(len(des_imgs)):
            image=requests.get(des_imgs[i])
            path_i=path+'/'+str(i)+'.jpg'
            f=open(path_i,'wb')
            f.write(image.content)
            f.close()
            print u'正在保存图片:',des_imgs[i]
            print u'图片路径:',path_i
            print u'文件:',path


        return item

需要在settings.py中使用这个管道

ITEM_PIPELINES = {
    'AVMOO.pipelines.AvmooPipeline': 300,
}

来重写一下下载中间件编写您自己的下载器中间件
middlewares.py

import random

class RandomUserAgentMiddleware(object):

    def __init__(self,agents):
        self.agents=agents

    @classmethod
    def from_crawler(cls,crawler):
        return cls(crawler.settings.getlist('USER_AGENTS'))

    @classmethod
    def from_settings(cls, settings):
        return cls(settings.getlist('USER_AGENTS'))

    def process_request(self,request,spider):
        us=random.choice(self.agents)
        print us
        request.headers.setdefault('User-Agent',us)

在settings.py中加入一个USER_AGENTS = […]的列表

DOWNLOADER_MIDDLEWARES = {
'AVMOO.middlewares.RandomUserAgentMiddleware': 543,}

就可以随机使用一个USER_AGENTS了

在settings.py中添加

CONCURRENT_ITEMS=100#默认Item并发数
CONCURRENT_REQUESTS=16#默认Request并发数
CONCURRENT_REQUESTS_PER_DOMAIN = 16#默认每个域名的并发数
CONCURRENT_REQUESTS_PER_IP = 0#每个ip的最大并发数,0表示忽略 

settings

未完待续。。。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/130247.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 深入理解Promise运行原理

    深入理解Promise运行原理

    2022年3月13日
    40
  • 用于重新编译的工具和命令

    用于重新编译的工具和命令

    2021年11月25日
    38
  • 谷歌浏览器驱动_谷歌驱动的配置与测试「建议收藏」

    谷歌浏览器驱动_谷歌驱动的配置与测试「建议收藏」下载地址使用selenium时,要确保所用的chrome浏览器跟chrome驱动版本对应,否则就会报错。驱动下载地址http://chromedriver.storage.proxy.ustclug.org/index.html77.0版本chromedriver.storage.proxy.ustclug.org/index.htmlhttp://chromedriver.storage.googlea…

    2022年6月14日
    55
  • 常见学习率衰减方式

    常见学习率衰减方式学习率学习率的作用​ 在机器学习中,监督式学习通过定义一个模型,并根据训练集上的数据估计最优参数。梯度下降法是一个广泛被用来最小化模型误差的参数优化算法。梯度下降法通过多次迭代,并在每一步中最小化成本函数(cost来估计模型的参数。学习率(learningrate),在迭代过程中会控制模型的学习进度。​ 在梯度下降法中,都是给定的统一的学习率,整个优化过程中都以确定的步长进行更新,在…

    2022年6月7日
    41
  • 手把手教你训练自己的Mask R-CNN图像实例分割模型(PyTorch官方教程)

    手把手教你训练自己的Mask R-CNN图像实例分割模型(PyTorch官方教程)近来在学习图像分割的相关算法,准备试试看MaskR-CNN的效果。关于MaskR-CNN的详细理论说明,可以参见原作论文https://arxiv.org/abs/1703.06870,网上也有大量解读的文章。本篇博客主要是参考了PyTorch官方给出的训练教程,将如何在自己的数据集上训练MaskR-CNN模型的过程记录下来,希望能为感兴趣的读者提供一些帮助。PyTorch官方教程(…

    2022年8月23日
    10
  • 计算机的存储容量一般用什么来表示_计算机常用的存储容量单位

    计算机的存储容量一般用什么来表示_计算机常用的存储容量单位存储容量是指存储器可以容纳的二进制信息量,用存储器中存储地址寄存器MAR的编址数与存储字位数的乘积表示。中文名存储容量所属学科计算机科学与技术存储容量单位简介语音网络上的所有信息都是以“位”(bit)为单位传递的,一个位就代表一个0或1。每8个位(bit)组成一个字节(byte)。字节是什么概念呢?一个英文字母就占用一个字节,也就是8位,一个汉字占用两个字节。一般位简写为小写字母“b”,字节简写为…

    2022年10月6日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号