Почему не удается записать запрос, который приводит к ошибке 404? - PullRequest
0 голосов
/ 25 апреля 2019
curl -I -w %{http_code}  http://quotes.money.163.com/f10/gszl_600024.html
HTTP/1.1 404 Not Found
Server: nginx

curl -I -w %{http_code}  http://quotes.money.163.com/f10/gszl_600023.html
HTTP/1.1 200 OK
Server: nginx

Это показывает, что http://quotes.money.163.com/f10/gszl_600024.html не существует, его код ошибки http 404; http://quotes.money.163.com/f10/gszl_600023.html существует, его код ошибки http 200.

Я хочу написать паука взапишите запрос, который приведет к ошибке 404.

  1. Добавить HTTPERROR_ALLOWED_CODES в middlewares.py.

    HTTPERROR_ALLOWED_CODES = [404,403,406, 408, 500, 503, 504]

  2. Добавить настройку журнала в settings.py.

    LOG_LEVEL = "CRITICAL"
    LOG_FILE = "mylog"

  3. Создай паука.

    import scrapy
    from info.items import InfoItem
    import logging
    
    class InfoSpider(scrapy.Spider):
        handle_httpstatus_list = [404]
        name = 'info'
        allowed_domains = ['quotes.money.163.com']
        start_urls = [ r"http://quotes.money.163.com/f10/gszl_600023.html",
                   r"http://quotes.money.163.com/f10/gszl_600024.html"]
    
        def parse(self, response):
            item = StockinfoItem()
            if(response.status == 200):logging.critical("url whose status is 200 : " + response.url)
            if(response.status == 404):logging.critical("url whose status is 404 : " + response.url)  
    

Открыть файл mylog после запуска паука.

2019-04-25 08:47:57 [root] CRITICAL: url whose status is 200 : http://quotes.money.163.com/
2019-04-25 08:47:57 [root] CRITICAL: url whose status is 200 : http://quotes.money.163.com/f10/gszl_600023.html

Почему для http://quotes.money.163.com/ существует статус 200?когда вы вводите http://quotes.money.163.com/f10/gszl_600023.html в браузере, для этого URL на сервере нет содержимого, он будет перенаправлен на http://quotes.money.163.com/ через 5 секунд, а http-код для http://quotes.money.163.com/ равен 200, поэтому здесь есть две строки состояния 200.

Что меня смутило, так это то, что в файле журнала нет такой информации о журнале, как

2019-04-25 08:47:57 [root] CRITICAL: url whose status is 404 : http://quotes.money.163.com/f10/gszl_600024.html

mylog.

Как заставить if(response.status == 404):logging.critical("url whose status is 404 : " + response.url) исполниться в моем scrapy1.6

1 Ответ

1 голос
/ 25 апреля 2019

Вы перенаправили с 404 страницы на главную. Таким образом, вы можете установить dont_redirect, и он покажет вам необходимый ответ. Попробуйте это:

class InfoSpider(scrapy.Spider):
    handle_httpstatus_list = [404]
    name = 'info'
    allowed_domains = ['quotes.money.163.com']
    start_urls = [
        r"http://quotes.money.163.com/f10/gszl_600023.html",
        r"http://quotes.money.163.com/f10/gszl_600024.html"
    ]

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, meta={'dont_redirect': True})

    def parse(self, response):
        if response.status == 200:
            logging.critical("url whose status is 200 : " + response.url)
        if response.status == 404:
            logging.critical("url whose status is 404 : " + response.url)

Итак, теперь я попадаю в свой журнал:

2019-04-25 08:09:23 [root] CRITICAL: url whose status is 200 : http://quotes.money.163.com/f10/gszl_600023.html
2019-04-25 08:09:23 [root] CRITICAL: url whose status is 404 : http://quotes.money.163.com/f10/gszl_600024.html
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...