瓜子二手车为什么没输出

瓜子二手车为什么没输出

https://img1.sycdn.imooc.com//climg/621766040998e53119201080.jpg

这是spider里面的代码
import scrapy
import json
from guazi_xhr.items import GuaziXhrItem


class GuaziSpider(scrapy.Spider):
    name = 'guazi'
    allowed_domains = ['guazi.com']
    # start_urls = ['http://guazi.com/']

    def starts_requests(self):
        with open("brand.txt", "r", encoding="utf-8") as f:
            brands_data = f.read()
        brands_list = json.loads(brands_data).get('data').get('common')
        for brand in brands_list:
            url = "https://mapi.guazi.com/car-source/carList/pcList?minor={}&sourceType=&ec_buy_car_list_ab=&location_city=&district_id=&tag=-1&license_date=&auto_type=&driving_type=&gearbox=&road_haul=&air_displacement=&emission=&car_color=&guobie=&bright_spot_config=&seat=&fuel_type=&order=7&key_word=&priceRange=0,-1&tag_types=&diff_city=&intention_options=&initialPriceRange=&monthlyPriceRange=&transfer_num=&car_year=&carid_qigangshu=&carid_jinqixingshi=&cheliangjibie=&page=1&pageSize=20&city_filter=13&city=13&guazi_city=13&versionId=0.0.0.0&osv=Unknown&platfromSource=wap".format(brand.get("value"))
            yield scrapy.Request(url=url,callback=self.parse)
            break


    def parse(self, response):
        data = response.json().get('data').get('postList')
        for item in data:
            url = "https://www.guazi.com/Detail?clueId={}".format(item.get("clue_id"))
            yield scrapy.Request(url = url, callback=self.parse_detail, dont_filter=True)

    def parse_detail(self,response):
        info = GuaziXhrItem()
        info['title'] = response.xpath("//h1[@class='titlebox']/text()").extract_first()
        info['price'] = response.xpath("//span[@class='price-num gzfont']/text()").extract_first()
        yield info

这个是配置文件代码

# Scrapy settings for yushu project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'yushu'

SPIDER_MODULES = ['yushu.spiders']
NEWSPIDER_MODULE = 'yushu.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'yushu.middlewares.YushuSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'yushu.middlewares.YushuDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'yushu.pipelines.YushuPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

这个是中间件代码

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter


class GuaziXhrSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class GuaziXhrDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class HandleDetail(object):
    """用户破解详情页的中间件"""

    # 直接携带cookie访问目标信息,而不是通过返回的js代码计算cookie
    def process_request(self, request, spider):
        # 如果说请求的URL里面有www.guazi.com/Detail并且request.cookie没有值的
        if "www.guazi.com/Detail" in request.url and not request.cookies:
            cookie_value = {"uuid": "badf427f-0079-443c-baad-37ec3cfe9553"}
            request.cookies = cookie_value
            # 重新发送请求,入队列
            return request


https://img1.sycdn.imooc.com//climg/6217669f09931ee619201080.jpg

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
好帮手慕凡 2022-02-25 10:33:07

同学,你好!

1、因为同学的代码有错误,但使用命令执行代码时选择了--nolog不打印日志,所以没有任何输出;

2、使用scrapy框架时,框架所规定的函数名不可以修改,修改会导致无法执行或报错,如下图:如将start_requests写为了starts_requests会导致scrapy框架找不到start_requests函数导致无法正常执行;

https://img1.sycdn.imooc.com//climg/62183e30098659aa07250405.jpg

3、setting.py文件中应将yushu修改为当前爬取网站相应的文件名称,同学也可以scrapy操作命令重新创建一个scrapy爬虫文件进行瓜子网站的爬取;

https://img1.sycdn.imooc.com//climg/62183f17094fbce405890409.jpg

祝学习愉快~


  • 提问者 __________千 #1

    https://img1.sycdn.imooc.com//climg/62189ed709a85a5519201080.jpg

    老师为什么读不出来这个文件

    2022-02-25 17:18:28
  • 好帮手慕凡 回复 提问者 __________千 #2

    同学,你好!

    以上错误是没又找到这个文件,同学检查一下文件路径是否正确,祝学习愉快~

    2022-02-25 17:34:33
  • 提问者 __________千 回复 好帮手慕凡 #3

    https://img1.sycdn.imooc.com//climg/6218a4410910220619201080.jpg

    https://img1.sycdn.imooc.com//climg/6218a4510993f28e19201080.jpg

    老师这个请求403被限制住了,该怎么解决

    2022-02-25 17:42:19
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师