Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

python - Scrapy spider crawls but does not scrape

I am trying to scrape the details of different companies from this website. The problem is that though the Spider seems to navigate through the pages, the data I need is not being extracted and saved. I get the message below from my logs (One of the pages with the details to be scraped can be found here). Please help me with this.

INFO: Scrapy 2.4.1 started (bot: yellowpages)
INFO: Versions: lxml 4.6.2.0, libxml2 2.9.5, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 20.3.0, Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)], pyOpenSSL 20.0.1 (OpenSSL 1.1.1i  8 Dec 2020), cryptography 3.3.1, Platform Windows-10-10.0.18362-SP0
INFO: Overridden settings:
{'BOT_NAME': 'yellowpages',
 'CONCURRENT_REQUESTS': 4,
 'FEED_EXPORT_ENCODING': 'utf-8',
 'LOG_FILE': 'log.txt',
 'LOG_FORMAT': '%(levelname)s: %(message)s',
 'LOG_LEVEL': 'INFO',
 'NEWSPIDER_MODULE': 'yellowpages.spiders',
 'SPIDER_MODULES': ['yellowpages.spiders'],
 'USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) '
               'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 '
               'Safari/537.36'}
INFO: Telnet Password: 74106c59dc8f08df
INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.feedexport.FeedExporter',
 'scrapy.extensions.logstats.LogStats',
 'scrapy.extensions.telnet.TelnetConsole']
INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'yellowpages.middlewares.YellowpagesDownloaderMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'yellowpages.middlewares.YellowpagesSpiderMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
INFO: Enabled item pipelines:
['yellowpages.pipelines.DuplicateItemFilter',
 'yellowpages.pipelines.YellowpagesPipeline']
INFO: Spider opened
INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
INFO: Spider opened: yellow
INFO: Spider opened: yellow
INFO: Telnet console listening on 127.0.0.1:6023
INFO: Crawled 701 pages (at 701 pages/min), scraped 0 items (at 0 items/min)
INFO: Crawled 1308 pages (at 607 pages/min), scraped 0 items (at 0 items/min)
INFO: Crawled 2008 pages (at 700 pages/min), scraped 0 items (at 0 items/min)
INFO: Received SIGINT, shutting down gracefully. Send again to force 
INFO: Closing spider (shutdown)
INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 2367951,
 'downloader/request_count': 2070,
 'downloader/request_method_count/GET': 2070,
 'downloader/response_bytes': 65108151,
 'downloader/response_count': 2070,
 'downloader/response_status_count/200': 2070,
 'dupefilter/filtered': 3,
 'elapsed_time_seconds': 185.198172,
 'finish_reason': 'shutdown',
 'finish_time': datetime.datetime(2021, 1, 21, 11, 41, 22, 400543),
 'log_count/INFO': 16,
 'request_depth_max': 23,
 'response_received_count': 2070,
 'scheduler/dequeued': 2070,
 'scheduler/dequeued/memory': 2070,
 'scheduler/enqueued': 2280,
 'scheduler/enqueued/memory': 2280,
 'start_time': datetime.datetime(2021, 1, 21, 11, 38, 17, 202371)}
INFO: Spider closed (shutdown)

Also, here are the contents of my Spider and items file. I run the spider with scrapy crawl -o results.json

yellow.py (the Spider)

import scrapy
from yellowpages.items import YellowpagesItem
from scrapy_selenium import SeleniumRequest

class YellowSpider(scrapy.Spider):
    name = 'yellow'
    allowed_domains = ['yellowpagesofafrica.com']
    start_urls = ['https://www.yellowpagesofafrica.com/']


    def start_requests(self):
        for url in self.start_urls:
            yield SeleniumRequest(url=url, callback=self.parse)

    def parse(self, response):
        urls = response.xpath('//div[@class="col-sm-12"]//div[@class="col-sm-4 col-xs-6 col-md-4 col-lg-3"]/a/@href').extract()

        for url in urls:
            yield SeleniumRequest(
                url = response.urljoin(url), callback = self.parse_country_page
            )
    def parse_country_page(self, response):
        urls = response.xpath('//div[@class="col-sm-12 col-lg-12 ct-u-marginBottom40"]//div[@class="row"]/a/@href').extract()

        for url in urls:
            yield SeleniumRequest(
                url = response.urljoin(url), callback = self.parse_companies_detail
            )

    def parse_companies_detail(self, response):
        country,industry = response.url.split('/')[-3:-1]
        names = response.xpath('//div[@class="col-sm-6 col-md-6 col-lg-4"]//div[@class="ct-product--tilte"]/text()').extract()
        names = [i.strip() for i in names]
    
        websites = response.xpath('//div[@class="row ct-js-search-results ct-showProducts--list ct-u-marginTop10"]//div[@class="col-sm-6 col-md-6 col-lg-4"]//div[@class="ct-product--description"]')
        for i,j in enumerate(websites):
            w = j.xpath('a/@href').extract()
            websites[i]= w if w else ""


        mails = numbers = []
        for i in response.xpath('//div[@class="row ct-js-search-results ct-showPproduct--description"]//div[@class="buttonShowCo"]'):
            id_ = i.xpath('@onclick').get().split("'")[-2]

            m = response.xpath(f'//*[@id="{id_}"]/a/@href').extract()
            mails.append(m if m else "")
            p = response.xpath(f'//*[@id="{id_}"]/text()').extract_first()
            numbers.append(p if p else "")

        for name, website, mail, number in zip(names, websites, mails, numbers):
            item = YellowpagesItem()
            item['name'] = name
            item['website'] = website
            item['mail'] = mail
            item['number'] = number
            item['country'] = country.title()
            item['industry'] = industry.title()
            print ('**parse_companies_detail:', item["name"], item["website"])
            yield item

        nxt = response.xpath('//div[@class="ct-pagination text-center"]/ul/li/a/@href').extract()
        if nxt:
            nxt = nxt[-1]
            if nxt!='#':
                yield SeleniumRequest(
                    url = response.urljoin(nxt), callback = self.parse_companies_detail
                )

items.py

from scrapy import Field, Item

class YellowpagesItem(Item):
    # define the fields for your item here like:
    name = Field()
    mail = Field()
    number = Field()
    website = Field()
    country = Field()
    industry = Field()
question from:https://stackoverflow.com/questions/65829676/scrapy-spider-crawls-but-does-not-scrape

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...