无法抓取动态内容(使用启动设置抓取)

时间:2020-07-29 23:37:36

标签: python python-3.x scrapy scrapy-splash dynamic-content

我正试图从this link的网页上抓取有关学校的内容,因此该页面主要由动态内容组成,因此我遵循了使用启动here的步骤

我成功使用以下命令在Mac OS上运行docker映像:

docker run -p 8050:8050 scrapinghub/splash

以下是修改后的settings.py的样子:

BOT_NAME = 'school_scrape'
SPIDER_MODULES = ['school_scrape.spiders']
NEWSPIDER_MODULE = 'school_scrape.spiders'
ROBOTSTXT_OBEY = True
SPLASH_URL = 'http://192.168.59.103:8050'
DOWNLOADER_MIDDLEWARES = {
    'scrapy_splash.SplashCookiesMiddleware': 723,
    'scrapy_splash.SplashMiddleware': 725,
    'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
}
SPIDER_MIDDLEWARES = {
    'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,
}
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'

下面是一个学校页面上动态内容的示例,我正在尝试从中获取值(在这种情况下为1、1、1、1):

school count

以下是Google chrome中的检查:

inspection

然后我将这一行添加到蜘蛛模块schools.py

school_count = response.xpath('//*[@class="school-count"]/text()')

这里是schools.py

from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor


class SchoolsSpider(CrawlSpider):
    name = 'schools'
    allowed_domains = ['greatschools.org']
    start_urls = [
        'https://www.greatschools.org/schools/districts/Connecticut/CT/',
        'https://www.greatschools.org/schools/districts/New_Jersey/NJ/'
    ]
    rules = (Rule(LinkExtractor(
        allow=['connecticut/', 'new-jersey/']), callback='parse_page', follow=True),)

    @staticmethod
    def parse_page(response):
        school_data = dict()
        school_data['title'] = response.xpath('//h1/text()').get()
        if not school_data['title'] or 'School' not in school_data['title']:
            return
        school_data['address'], school_data['phone'], *_ = response.xpath(
            '//*[@class="content"]/text()').extract()
        school_count = response.xpath('//*[@class="school-count"]/text()')
        print(school_count)
        yield {label: value.strip() for label, value in school_data.items()}

但是,它导致列表为空,这意味着它无法检测动态内容。有没有如何在不使用硒的情况下使其工作的想法?

我尝试了Wim Hermans的建议,但是它不起作用,这是日志:

2020-07-30 22:10:57 [scrapy.utils.log] INFO: Scrapy 2.2.1 started (bot: school_scrape)
2020-07-30 22:10:57 [scrapy.utils.log] INFO: Versions: lxml 4.5.0.0, libxml2 2.9.10, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 20.3.0, Python 3.8.3 (default, May 27 2020, 20:54:22) - [Clang 11.0.3 (clang-1103.0.32.59)], pyOpenSSL 19.1.0 (OpenSSL 1.1.1g  21 Apr 2020), cryptography 3.0, Platform macOS-10.15.6-x86_64-i386-64bit
2020-07-30 22:10:57 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor
2020-07-30 22:10:57 [scrapy.crawler] INFO: Overridden settings:
{'BOT_NAME': 'school_scrape',
 'DUPEFILTER_CLASS': 'scrapy_splash.SplashAwareDupeFilter',
 'HTTPCACHE_STORAGE': 'scrapy_splash.SplashAwareFSCacheStorage',
 'NEWSPIDER_MODULE': 'school_scrape.spiders',
 'SPIDER_MODULES': ['school_scrape.spiders']}
2020-07-30 22:10:57 [scrapy.extensions.telnet] INFO: Telnet Password: a22c386624bcd3a4
2020-07-30 22:10:57 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.memusage.MemoryUsage',
 'scrapy.extensions.logstats.LogStats']
2020-07-30 22:10:57 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy_splash.SplashCookiesMiddleware',
 'scrapy_splash.SplashMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2020-07-30 22:10:57 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy_splash.SplashDeduplicateArgsMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2020-07-30 22:10:57 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2020-07-30 22:10:57 [scrapy.core.engine] INFO: Spider opened
2020-07-30 22:10:57 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2020-07-30 22:10:57 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2020-07-30 22:10:57 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.greatschools.org/schools/districts/Connecticut/CT/> (referer: None)
2020-07-30 22:10:57 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.greatschools.org/schools/districts/New_Jersey/NJ/> (referer: None)
2020-07-30 22:10:57 [py.warnings] WARNING: /usr/local/lib/python3.8/site-packages/scrapy_splash/request.py:41: ScrapyDeprecationWarning: Call to deprecated function to_native_str. Use to_unicode instead.
  url = to_native_str(url)

2020-07-30 22:10:57 [scrapy.spidermiddlewares.offsite] DEBUG: Filtered offsite request to 'www.greatschools.org': <GET https://www.greatschools.org/connecticut/hartford/achievement-first-hartford-ac/>
2020-07-30 22:10:57 [scrapy.core.engine] INFO: Closing spider (finished)
2020-07-30 22:10:57 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 505,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,
 'downloader/response_bytes': 45862,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 2,
 'elapsed_time_seconds': 0.609385,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2020, 7, 30, 20, 10, 57, 926858),
 'log_count/DEBUG': 3,
 'log_count/INFO': 10,
 'log_count/WARNING': 1,
 'memusage/max': 49856512,
 'memusage/startup': 49856512,
 'offsite/domains': 1,
 'offsite/filtered': 882,
 'request_depth_max': 1,
 'response_received_count': 2,
 'scheduler/dequeued': 2,
 'scheduler/dequeued/memory': 2,
 'scheduler/enqueued': 2,
 'scheduler/enqueued/memory': 2,
 'start_time': datetime.datetime(2020, 7, 30, 20, 10, 57, 317473)}
2020-07-30 22:10:57 [scrapy.core.engine] INFO: Spider closed (finished)

1 个答案:

答案 0 :(得分:1)

我认为问题在于您是在执行正常的scrapy请求而不是Splash Request。我认为您不能在这种情况下使用CrawlSpider,因为您将不得不覆盖and parse方法。这就是我的写法:

from scrapy_splash import SplashRequest


class SchoolsSpider(Spider):
    name = 'schools'
    allowed_domains = ['greatschools.org']
    start_urls = [
        'https://www.greatschools.org/schools/districts/Connecticut/CT/',
        'https://www.greatschools.org/schools/districts/New_Jersey/NJ/'
    ]

    def parse(self, response):
        school_links = response.xpath(
            '//*[@class="city-district-link"]/a/@href'
        ).extract()
        for school_link in school_links:
            yield SplashRequest(response.urljoin(school_link),
                                callback=self.parse_page,
                                endpoint='render.html',
                                args={'wait': 0.5},
                                )

    def parse_page(self, response):
        school_data = dict()
        school_data['title'] = response.xpath('//h1/text()').get()
        if not school_data['title'] or 'School' not in school_data['title']:
            return
        school_data['address'], school_data['phone'], *_ = response.xpath(
            '//*[@class="content"]/text()').extract()
        school_count = response.xpath('//*[@class="school-count"]/text()')
        print(school_count)
        yield {label: value.strip() for label, value in school_data.items()}