即使状态为301,如何获取响应文本?

时间:2019-04-29 07:49:19

标签: python python-3.x web-scraping scrapy

我已经草率地编写了一个脚本,以从网页中获取响应文本。问题是我的脚本总是仅由于存在None而打印301 status

有什么方法可以控制我从301开始的状态并在控制台中打印响应吗?

这是我尝试过的:

import scrapy
from scrapy.crawler import CrawlerProcess

class ResponseSpider(scrapy.Spider):
    name = "transfermarkt"
    handle_httpstatus_list = [301]
    start_urls = ["https://www.transfermarkt.es/guti/profil/spieler/6079"]

    def parse(self,response):
        print(response.text)

if __name__ == "__main__":
    c = CrawlerProcess({'USER_AGENT':'Mozilla/5.0'})
    c.crawl(ResponseSpider)
    c.start()

当前显示的内容:

2019-04-29 13:39:41 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6024
2019-04-29 13:39:42 [scrapy.core.engine] DEBUG: Crawled (301) <GET https://www.transfermarkt.es/guti/profil/spieler/6079> (referer: None)

2019-04-29 13:39:43 [scrapy.core.engine] INFO: Closing spider (finished)
2019-04-29 13:39:43 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 220,
 'downloader/request_count': 1,
 'downloader/request_method_count/GET': 1,
 'downloader/response_bytes': 511,
 'downloader/response_count': 1,
 'downloader/response_status_count/301': 1,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2019, 4, 29, 7, 39, 43, 50813),
 'log_count/DEBUG': 1,
 'log_count/INFO': 9,
 'response_received_count': 1,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2019, 4, 29, 7, 39, 41, 869745)}
2019-04-29 13:39:43 [scrapy.core.engine] INFO: Spider closed (finished)

1 个答案:

答案 0 :(得分:2)

在这种情况下:
https://www.transfermarkt.es/guti/profil/spieler/6079的请求(URL A -301响应)被重定向到 https://www.transfermarkt.es/zeljko-kalac/profil/spieler/6079(网址 B -200响应)

Scrapy默认使用RedirectMiddlewaredocscode)处理重定向3xx状态
要解析网页 B ,您只需从代码中删除handle_httpstatus_list = [301]

在大多数情况下,301响应不包含html代码。响应头中包含的所有相关数据。
如果您需要打印来自url A 的301响应中的相关数据:

  1. 不要删除handle_httpstatus_list = [301]
  2. 使用response.headers数据代替response.text