Scrapy Python填写表单并获取数据

时间:2015-10-20 17:15:46

标签: python forms web-scraping scrapy scrapy-spider

我正在尝试使用Scrapy从网站自动下载数据。

我需要做的是:

  • 使用我的凭据登录网站

  • 通过在“RIC”行上编写代码并选择感兴趣的时段来选择我想要的数据 enter image description here

  • 点击“获取数据”后,会生成.csv文件,我可以从'download /'url下载它,我的所有文件都可以这样下载: enter image description here

我可以使用'FormRequest'登录。因此,我想要做同样的事情来填充'RIC'代码并单击'获取数据'按钮但这会失败。 (我现在不改变日期只是为了理解它是如何工作的)

这是我的代码:

class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["myDomain"]
start_urls = [
    "http://myDomain/dataServices/"
]

def parse(self, response):
    return scrapy.FormRequest.from_response(
        response,
        formdata={'username': 'myName', 'password': 'myPass'},
        callback=self.after_login
    )

def after_login(self, response):
    # check login succeed before going on
    if "Your email adress and password did not match" in response.body:
        print("\n\nFAIL\n\n")
        self.logger.error("Login failed")
        return

    else:
        print("\n\n LOGIN SUCCESSFUL \n\n")

        filename = response.url.split("/")[-2] + '.html'
        with open(filename, 'wb') as f:
            f.write(response.body)
        ## THIS FAILS !!!
        return scrapy.http.FormRequest.from_response(
            response,
            formxpath='//input[@value = ""]',
            formdata={'value': 'DJ@'},
            clickdata={'value': 'Get data'},
            callback= self.foo
        )

这是表单的html:

<form method="post" action="."><div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='6b16efca43f6d99b34e46561ebf6a1ab' /></div>
RIC (s) : <input name="ric" value=""  size="20" />(one or several rics separated by spaces)<br /><br />
Begin date : <script>DateInput('beginDate', true, 'YYYYMMDD','20110303')</script>
<!-- <input type="button" onClick="alert(this.form.orderdate.value)" value="Show date value passed"> -->

<!--<input name="beginDate" value=""  size="60" /> --><br />
End Date : <script>DateInput('endDate', true, 'YYYYMMDD','20110306') </script><br />
<input type="submit" value="Get data" /> </form>

我从日志中得到的错误:

2015-10-20 18:49:53 [scrapy] DEBUG: Retrying <POST http://myDomain/dataServices/> (failed 1 times): 500 Internal Server Error
2015-10-20 18:49:53 [scrapy] DEBUG: Retrying <POST http://myDomain/dataServices/> (failed 2 times): 500 Internal Server Error
2015-10-20 18:49:53 [scrapy] DEBUG: Gave up retrying <POST http://myDomain/dataServices/> (failed 3 times): 500 Internal Server Error
2015-10-20 18:49:53 [scrapy] DEBUG: Crawled (500) <POST http://myDomain/dataServices/> (referer: http://myDomain/dataServices/)
2015-10-20 18:49:53 [scrapy] DEBUG: Ignoring response <500 http://myDomain/dataServices/>: HTTP status code is not handled or not allowed

你知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

'formxpath'kwarg应该是一个xpath,它实际上包含一个表单元素,如documentation中所示 - “将使用与xpath匹配的第一个表单”。因此,如果html页面中只有一个表单,则不需要使用'formxpath'。

在这种情况下,在提交表单时你需要适当地构造'formdata',它应该有ric,beginDate和endDate的值(基本上所有表单元素如输入,选择等在html中没有默认值或者其中需要更改/覆盖值,就像您的代码对登录表单提交一样。

    return scrapy.FormRequest.from_response( response,
        formdata={'ric': 'Some RIC Code', 'beginDate': '20110303', 'endDate': '20110306'},
        callback=self.after_ric_form_submit
    )

def after_ric_form_submit(self, response):
    #go to download page...
    yield Request('http://myDomain/download/', callback = self.download_csv)