使用 scrapy-splash 单击按钮

Hom*_*lli 5 python scrapy

我正在尝试使用Scrapy-splash单击我被重定向到的页面上的按钮。

我已经测试过手动单击该页面,并且在单击表示同意的按钮后,我被重定向到正确的页面。我编写了一个小脚本,用于在重定向到该页面时单击该按钮,但这不起作用。

我在下面包含了我的蜘蛛的片段 - 我的代码中是否缺少某些内容?:

from sys import path
import os

dir_path = os.path.dirname(os.path.realpath(__file__))
path.append(dir_path)

import scrapy
from scrapy_splash import SplashRequest

script="""
function main(splash)
    splash:wait(1)
    splash:runjs('document.querySelector("form.consent-form").submit()')
    splash:wait(1)
    return {
        html = splash:html(),
    }
end
"""


class FoobarSpider(scrapy.Spider):
    name = "foobar"          

    def start_requests(self):
        urls = ['https://uk.finance.yahoo.com/quote/ANTO.L?p=ANTO.L']

        for url in urls:
            yield SplashRequest(url=url, callback=self.parse,
                    endpoint='render.html',
                    args={'wait': 3},
                    meta = {'yahoo_url': url }
                )



    def parse(self, response):
        url = response.url

        with open('temp.html', 'wb') as f:
            f.write(response.body)

        if 'https://guce.' in url:
            print('About to attempt to authenticate ...')
            yield SplashRequest(
                                    url, 
                                    callback = self.get_price, 
                                    endpoint = 'execute',
                                    args = {'lua_source': script, 'timeout': 5},
                                    meta = response.meta 
                                )

        else:
            self.get_price(response)




    def get_price(self, response):    
        print("Get price called!")
        yahoo_price = None          

        try:
            # Get Price ...
            temp1 = response.css('div.D\(ib\).Mend\(20px\)')
            if temp1 and len(temp1) > 1:
                temp2 = temp1[1].css('span')
                if len(temp2) > 0:
                    yahoo_price = temp2[0].xpath('.//text()').extract_first().replace(',','') 

            if not yahoo_price:
                val = response.css('span.Trsdu\(0\.3s\).Trsdu\(0\.3s\).Fw\(b\).Fz\(36px\).Mb\(-4px\).D\(b\)').xpath('.//text()').extract_first().replace(',','')
                yahoo_price = val


        except Exception as err:
            pass           


        print("Price is: {0}".format(yahoo_price))


    def handle_error(self, failure):
        pass
Run Code Online (Sandbox Code Playgroud)

如何解决此问题,以便我能够正确给予同意,以便我被定向到我想要的页面?

Zev*_*Zev 2

不要单击按钮,而是尝试提交表单:

document.querySelector("form.consent-form").submit()
Run Code Online (Sandbox Code Playgroud)

我尝试在控制台中运行 JavaScript 命令input.btn.btn-primary.agree").click(),并收到错误消息“哎呀,出了问题”,但使用上述代码提交表单时会加载页面。

因为我不在欧洲,所以我无法完全重新创建您的设置,但我相信这应该可以帮助您解决问题。我的猜测是这个脚本干扰了该.click()方法。