无法抓取动态内容(带有启动设置的抓取)

Posted

技术标签:

【中文标题】无法抓取动态内容(带有启动设置的抓取)【英文标题】:Failing to scrape dynamic content (scrapy with splash settings) 【发布时间】:2020-11-19 15:49:31 【问题描述】:

我正在尝试从this link 中抓取有关学校的内容,该页面主要由动态内容组成,因此我按照使用 splash here 的步骤进行操作

我使用这个命令成功地在我的 mac os 上运行了 docker 镜像:

docker run -p 8050:8050 scrapinghub/splash

scrapy 的 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)提取值的其中一个学校页面上的动态内容示例:

这是谷歌浏览器中的检查:

我将这一行添加到蜘蛛模块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】:

我认为问题在于您正在执行普通的scrapy Requests而不是Splash Requests。在这种情况下,我认为您不能使用 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()


【讨论】:

日志中提到了问题:2020-07-30 22:10:57 [scrapy.spidermiddlewares.offsite] DEBUG: Filtered offsite request to 'www.greatschools.org': &lt;GET https://www.greatschools.org/connecticut/hartford/achievement-first-hartford-ac/&gt; 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: 我不明白 - 它存在于“allowed_domains”中,因此不应被过滤掉。我无法复制我这边的问题 - 也许您可以在您的请求中使用dont_filter=True

以上是关于无法抓取动态内容(带有启动设置的抓取)的主要内容,如果未能解决你的问题,请参考以下文章

使用 python-Scrapy 抓取动态内容

C#利用phantomJS抓取AjAX动态页面

为啥浏览器可以保存网页中js动态内容,用java编写的爬虫却无法抓取

我可以设置 textarea 的调整大小抓取器的样式吗?

抓取动态数据硒 - 无法定位元素

python 如何抓取动态页面内容?