Use scrapy + splash return html

橙三吉。 提交于 2020-01-05 03:18:08

问题


I'm trying to figure out scrapy and splash. As an exercise, I tried to make splash click on the button on the following javascript heavy website: http://thestlbrowns.com/ and then return the html of the newly rendered page.

My code looks like this:

import scrapy
import json
from scrapy import Request
class MySpider(scrapy.Spider):
    name = 'spiderman'
    domain = ['web']
    start_urls = ['http://thestlbrowns.com/']

    def start_requests(self):
        script = """
         function main(splash)
             local url = splash.args.url
             assert(splash:go(url))
             assert(splash:wait(1))

             assert(splash:runjs("$('#title.play-ball > a:first-child').click()"))
             assert(splash:wait(1))

             -- return result as a JSON object
             return {
                 html = splash:html(),
                 -- we don't need screenshot or network activity
                 --png = splash:png(),
                 --har = splash:har(),
             }
         end
        """

        for url in self.start_urls:
            yield Request(url, self.parse, meta={'splash': {'args':{'lua_source': script},'endpoint':'execute',}})

    def parse(self, response):
        splash_json = json.loads(response.body_as_unicode())

However when I run this code I get the following output:

$ scrapy crawl spiderman
2017-01-12 14:19:03 [scrapy.utils.log] INFO: Scrapy 1.3.0 started (bot: myScrapingProject)
2017-01-12 14:19:03 [scrapy.utils.log] INFO: Overridden settings: {'BOT_NAME': 'myScrapingProject', 'DOWNLOAD_DELAY': 0.25, 'DUPEFILTER_CLASS': 'scrapy_splash.SplashAwareDupeFilter', 'HTTPCACHE_STORAGE': 'scrapy_splash.SplashAwareFSCacheStorage', 'NEWSPIDER_MODULE': 'myScrapingProject.spiders', 'SPIDER_MODULES': ['myScrapingProject.spiders'], 'USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.7'}
2017-01-12 14:19:03 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.logstats.LogStats']
2017-01-12 14:19:03 [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.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-01-12 14:19:03 [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']
2017-01-12 14:19:03 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2017-01-12 14:19:03 [scrapy.core.engine] INFO: Spider opened
2017-01-12 14:19:03 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2017-01-12 14:19:03 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2017-01-12 14:19:16 [scrapy_splash.middleware] WARNING: Bad request to Splash: {'error': 400, 'info': {'error': "bad argument #2 to 'assert' (string expected, got table)", 'line_number': 8, 'source': '[string "..."]', 'message': 'Lua error: [string "..."]:8: bad argument #2 to \'assert\' (string expected, got table)', 'type': 'LUA_ERROR'}, 'description': 'Error happened while executing Lua script', 'type': 'ScriptError'}
2017-01-12 14:19:16 [scrapy.core.engine] DEBUG: Crawled (400) <POST http://localhost:8050/execute> (referer: None)
2017-01-12 14:19:16 [scrapy.spidermiddlewares.httperror] INFO: Ignoring response <400 http://thestlbrowns.com/>: HTTP status code is not handled or not allowed
2017-01-12 14:19:16 [scrapy.core.engine] INFO: Closing spider (finished)
2017-01-12 14:19:16 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 1222,
 'downloader/request_count': 1,
 'downloader/request_method_count/POST': 1,
 'downloader/response_bytes': 471,
 'downloader/response_count': 1,
 'downloader/response_status_count/400': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 1, 12, 13, 19, 16, 846242),
 'log_count/DEBUG': 2,
 'log_count/INFO': 8,
 'log_count/WARNING': 1,
 'response_received_count': 1,
 'scheduler/dequeued': 2,
 'scheduler/dequeued/memory': 2,
 'scheduler/enqueued': 2,
 'scheduler/enqueued/memory': 2,
 'splash/execute/request_count': 1,
 'splash/execute/response_count/400': 1,
 'start_time': datetime.datetime(2017, 1, 12, 13, 19, 3, 417278)}
2017-01-12 14:19:16 [scrapy.core.engine] INFO: Spider closed (finished)

Q: Does anyone know how to fix this/what I'm doing wrong?

EDIT: When I add script = quote(script) before passing the script to splash, I get the following error output:

Message: 'Bad request to Splash: {\'type\': \'ScriptError\', \'description\': \'Error happened while executing Lua script\', ' \
         '\'error\': 400, \'info\': {\'error\': "unexpected symbol near \'%\'", \'type\': \'LUA_INIT_ERROR\', \'line_number\': 1, ' \
         '\'source\': \'[string "%0A%20%20%20%20%20%20%20%20%20function%20main..."]\',' \
         ' \'message\': \'[string "%0A%20%20%20%20%20%20%20%20%20function%20main..."]:1: unexpected symbol near \\\'%\\\'\'}}'

回答1:


Splash response does contain some hints:

{'description': 'Error happened while executing Lua script',
 'error': 400,
 'info': {'error': "bad argument #2 to 'assert' (string expected, got table)",
          'line_number': 8,
          'message': 'Lua error: [string "..."]:8: bad argument #2 to \'assert\' (string expected, got table)',
          'source': '[string "..."]',
          'type': 'LUA_ERROR'},
 'type': 'ScriptError'}

If you try your script in Splash's web interface (it is your friend!), you have the same error, coming from this line:

assert(splash:runjs("$('#title.play-ball > a:first-child').click()"))

If you change that Lua script a bit, catching the error (by the way, I believe you meant .title.play-ball > a:first-child because there's no element with id="title"):

function main(splash)
     local url = splash.args.url
     assert(splash:go(url))
     assert(splash:wait(1))

     -- go back 1 month in time and wait a little (1 second)
     ok, err = splash:runjs("$('.title.play-ball > a:first-child').click()")
     assert(splash:wait(1))

     -- return result as a JSON object
     return {
         html = splash:html(),
         error = err
         -- we don't need screenshot or network activity
         --png = splash:png(),
         --har = splash:har(),
     }
 end

and running it in the web interface, you get an "error" object in the response, which shows:

error: Object
    js_error: "ReferenceError: Can't find variable: $"
    js_error_message: "Can't find variable: $"
    js_error_type: "ReferenceError"
    message: "JS error: \"ReferenceError: Can't find variable: $\""
    splash_method: "runjs"
    type: "JS_ERROR"

It appears the $ magic is not working on that website. You can use it in Chrome console for example, but with Splash you probably/apparently need to load jQuery (or something similar), with splash:autoload usually. For example:

function main(splash)
     assert(splash:autoload("https://code.jquery.com/jquery-3.1.1.min.js"))
     local url = splash.args.url
     assert(splash:go(url))
     assert(splash:wait(1))

     -- go back 1 month in time and wait a little (1 second)
     ok, err = splash:runjs("$('.title.play-ball > a:first-child').click()")
     assert(splash:wait(1))

     -- return result as a JSON object
     return {
         html = splash:html(),
         error = err
         -- we don't need screenshot or network activity
         --png = splash:png(),
         --har = splash:har(),
     }
 end

Note that this JavaScript code did not work for me with Splash (the screenshot did not show the "History" thing).

But I tried with the following in the web interface, and I got the "History" show (in the png screenshot -- which is commented here):

function main(splash)
     -- no need to load jQuery when you use splash:select
     --assert(splash:autoload("https://code.jquery.com/jquery-3.1.1.min.js"))
     local url = splash.args.url
     assert(splash:go(url))
     assert(splash:wait(15))

     local element = splash:select('.title.play-ball > a:first-child')
     local bounds = element:bounds()
     assert(element:mouse_click{x=bounds.width/2, y=bounds.height/2})
     assert(splash:wait(5))

     -- return result as a JSON object
     return {
         html = splash:html(),
         -- we don't need screenshot or network activity
         --png = splash:png(),
         --har = splash:har(),
     }
 end

Indeed, Splash 2.3 has helpers for that kind of interaction (e.g clicking on an element). See for example splash:select and element:mouse_click

Also note that I increased the wait() values.




回答2:


You need to "quote" your script before you pass it to Splash:

script = """Your script"""
from urllib.parse import quote
script = quote(script)
# 'Your%20script'


来源:https://stackoverflow.com/questions/41614472/use-scrapy-splash-return-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!