首页 > 解决方案 > scrapy 响应与页面源完全不同

问题描述

我正在尝试使用scrapy shell进入应该是一个公共网站的“ykc1.greatwestlife.com”,尽管如果我手动查看页面源代码会有很多事情,但我无法使用scrapy得到正确的响应。

scrapy shell 响应结果

在这种情况下我需要使用scrapy-splash吗?有任何想法吗?谢谢

标签: pythonweb-scrapingscrapyscrapy-splash

解决方案


您实际上可以看到两个背靠背请求,由

      <head>
        <script language="javascript">
            document.cookie = "cmsUserPortalLocale=en;path=/";
            document.cookie = "cmsTheme=advgwl;path=/";    
            document.cookie = "siteBrand="+escape(location.hostname)+"; path=/";
            window.location.reload(true);
        </script>

背靠背的请求

第一个请求要小得多,并且可能会导致您遇到的情况。值得庆幸的是,由于 cookie 看起来是静态的,因此您可以很容易地重现该行为:

def parse(self, response):
    # this is required because the response that arrives to parse()
    # has session cookies but we need to add 3 more to them
    new_cookies = {
      "cmsUserPortalLocale": "en",
      "cmsTheme": "advgwl",
      "siteBrand": "ykc1.greatwestlife.com",
    }
    yield response.follow(url=request.url, cookies=new_cookies,
                          callback=self.parse_home)

def parse_home(self, response):
    # and now you have the full body

推荐阅读