2

我正在使用 scrapy、splash 和 scrapy_splash 来抓取目录网站。

该网站使用表单 POST 打开一个新的项目详细信息页面。

有时,项目详细信息页面会在 Splash 中显示默认错误页面(与 HTTP 状态无关),但是如果我再次重新发布表单,则返回项目详细信息。我仍在调查响应的根本原因。这似乎更像是一个时间问题,而不是 n 个请求后的特定检查。

作为一种解决方法,我使用 splash:on_response 方法在收到错误页面时重试表单发布。

我希望能够记录失败的尝试以供以后手动处理。是否有收集这些信息的最佳实践或标准方法?

function main(splash)
    if splash.args.cookies then
        splash:init_cookies(splash.args.cookies)
    end   

    function web_request()
        if splash.args.http_method == 'GET' then            
            assert(splash:go{
                url=splash.args.url,
                headers=splash.args.headers,
                http_method=splash.args.http_method,
                body=splash.args.body,
            })
        else
            assert(splash:go{
                url=splash.args.url,
                headers=splash.args.headers,
                http_method=splash.args.http_method,
                body=splash.args.body,
                formdata=splash.args.formdata,
             })
        end
    end

    --- AREA OF THE CODE UNDER QUESTION
    local retry_max = 3
    local retry_count = 0
    splash:on_response(function (response)
        if string.find(response.url, 'error_check.html') ~= nil then
            if retry_count <= retry_max then
                retry_count = retry_count + 1
                web_request()
            else
                --- Not sure how to capture this in the item pipeline
                --- Also, I would like to capture the form post details
                --- such as the form data and headers
                error('Max retry exceeded' .. response)
            end
        end
    end)

    web_request()
    assert(splash:wait(0.5))

    local entries = splash:history()
    local last_response = entries[#entries].response

    return {
        url = splash:url(),
        headers = last_response.headers,
        http_status = last_response.status,
        cookies = splash:get_cookies(),
        html = splash:html(),
        har = splash:har(),
        retry_count = retry_count
    }
end
4

0 回答 0