2017-01-12 45 views
2

我想弄清楚scrapy和飞溅。作为一个练习,我试图点击下面的JavaScript重磅网站上的按钮:http://thestlbrowns.com/,然后返回新呈现页面的html。使用scrapy +飞溅返回html

我的代码如下所示:

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()) 

然而,当我运行此代码,我得到以下输出:

$ 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) 

问:没有人知道如何解决这个问题/我做错了吗?

编辑:当我路过脚本飞溅前加script = quote(script),我碰到下面的错误输出:

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 \\\'%\\\'\'}}' 

回答

6

飞溅应答包含一些提示:

{'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'} 

如果你尝试你得离谱PT在飞溅的Web界面(这是你的朋友!),你有同样的错误,从该行未来:

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

如果更改的Lua脚本一点,顺便捕捉错误(我相信你的意思.title.play-ball > a:first-child,因为有与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 

,并在网络界面运行它,你得到的回应是“错误”的对象,这表明:

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" 

看来$魔法在该网站上不起作用。例如,您可以在Chrome控制台中使用它,但通过Splash,您可能/显然需要加载jQuery(或类似的东西),通常为splash:autoload。例如:

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 

请注意,此JavaScript代码在Splash(我的屏幕截图未显示“历史记录”事件)时无法使用。

但我试图在Web界面下面,我得到了“历史”节目(在PNG截图 - 这是在这里评论):

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 

事实上,飞溅2.3有帮手这种交互(例如点击一个元素)。请参阅splash:selectelement:mouse_click

另请注意,我增加了wait()值。

+0

非常感谢你,真是一个好的答案!你有什么提示,我可以在哪里可以学到更多关于如何使用lua与splash/javascript?非常感谢您指出我可以使用splash API! – titusAdam

+0

不幸的是,我很喜欢Splash脚本。 –

0

你需要“引用”你的脚本,你通过它之前的Splash:

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

当我这样做时,我得到一个新的错误;看我的编辑。 – titusAdam