Scrapy FormRequest如何检查是否需要URL

时间:2017-04-02 13:45:48

标签: python-2.7 web-scraping scrapy

我是scrapy和一般网络技术的新手。

在处理scrapy示例时执行自动登录。我遇到了1个字段,引用网址。我想知道我什么时候需要这个。

        return scrapy.FormRequest.from_response(
            response,
            url='www.myreferrer.com', #when do i need this ???
            formnumber=1,
            formdata=self.data['formdata'],
            callback=self.after_login
        )

我使用和不使用它进行测试,它在两种情况下均可用。

我知道引用网址是为了安全,但我如何从html代码确定我需要或不需要这个? 的 ADDON 以下html表单需要定义url:

    <form id="login" enctype="multipart/form-data" method="post" action="https:///myshop.com/login/index.php?route=account/login">
        I am a returning customer.<br>
        <br>
        <b>E-Mail Address:</b><br>
        <input type="text" name="email">
        <br>
        <br>
        <b>Password:</b><br>
        <input type="password" name="password">
        <br>
        <a href="https:///myshop.com/login/index.php?route=account/forgotten">Forgotten Password</a><br>
        <div style="text-align: right;"><a class="button" onclick="$('#login').submit();"><span>Login</span></a></div>
                  </form>`

1 个答案:

答案 0 :(得分:1)

class FormRequest(Request):

# delete some code here

    @classmethod
    def from_response(cls, response, formname=None, formid=None, formnumber=0, formdata=None,
                  clickdata=None, dont_click=False, formxpath=None, formcss=None, **kwargs):
    url = _get_form_url(form, kwargs.pop('url', None))


    def _get_form_url(form, url):
        if url is None:
            return urljoin(form.base_url, form.action)
        return urljoin(form.base_url, url)

如果url为空,则会使用form标记的操作属性来获取网址。

如果url不为空,则使用您提供给它的网址。

base_url来自response

def _get_form(response, formname, formid, formnumber, formxpath):
    """Find the form element """
    root = create_root_node(response.text, lxml.html.HTMLParser,
                            base_url=get_base_url(response))

因此,当action属性不存在或者登录请求未发送到操作URL时,您需要传递参数。

相关问题