2017-08-07 226 views
0

這是我簡單的蜘蛛的代碼(剛開始):Scrapy,如何仍然得到與狀態302(重定向)內容

def start_requests(self): 
    urls = [ 
     'http://www.liputan6.com/search?q=bubarkan+hti&type=all', 
    ] 
    for url in urls: 
     yield scrapy.Request(url=url, callback=self.parse) 

def parse(self, response): 
    page = response.url.split("/")[-2] 
    filename = 'quotes-%s.html' % page 
    with open(filename, 'wb') as f: 
     f.write(response.body) 
    self.log('Saved file %s' % filename) 

與瀏覽器,我可以訪問網址「http://www.liputan6.com/search?q=bubarkan+hti&type=all」正常。但是,爲什麼這種scrapy我得到302的響應,我無法抓取的頁面..

請誰能告訴我,如何解決它..

回答

0

好像網頁期待一些餅乾,如果這些餅乾沒有發現它重定向到索引頁面。

我得到它的工作通過增加這些cookie:js_enabled=true; is_cookie_active=true;

$scrapy shell "http://www.liputan6.com/search?q=bubarkan+hti&type=all" 
# redirect happens 
>[1]: response.url 
<[1]: 'http://www.liputan6.com' 
# add cookie to request: 
>[2]: request.headers['Cookie'] = 'js_enabled=true; is_cookie_active=true;' 
>[3]: fetch(request) 
# redirect no longer happens 
>[4]: response.url 
<[4]: 'http://www.liputan6.com/search?q=bubarkan+hti&type=all' 

編輯:您的代碼嘗試:

def start_requests(self): 
    urls = [ 
     'http://www.liputan6.com/search?q=bubarkan+hti&type=all', 
    ] 
    for url in urls: 
     req= scrapy.Request(url=url, callback=self.parse) 
     req.headers['Cookie'] = 'js_enabled=true; is_cookie_active=true;' 
     yield req 

def parse(self, response): 
    # 200 response here 
+0

喜@Granitosaurus感謝您的諮詢, 我從腳本運行scrapy, http://scrapy.readthedocs.io/en/latest/topics/practices.html#run-scrapy-from-a-script 在哪裏添加代碼「cookie」? – rahmatheruka

+0

嗨,我已經嘗試了你的建議,但我得到了2017-08-08 07:15:58 [scrapy.downloadermiddlewares.redirect] DEBUG:重定向(302)到 2017-08-08 07:15:59 [scrapy.core.engine] DEBUG:Crawled(200)(referer:無)。我仍然得到重定向302 – rahmatheruka

+0

@rahmatheruka你可以嘗試我的編輯代碼? – Granitosaurus