刮取时刮取的网站认证令牌过期

2024-04-26 14:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

为了在未来180天内抓取某个特定网站,必须获得身份验证令牌才能获取要刮取的json数据。在抓取时,令牌过期,HTTP响应返回状态代码401“Unauthorized”。如何将新令牌放入刮刀并继续刮取?感谢任何帮助。

def start_requests(self):
    return [Request(url=AUTHORIZATION_URL, callback=self.request_ride_times)]

def request_ride_times(self, response):
    # parse json data
    data = json.loads(response.body)

    # get auth token
    auth = '{}'.format(data['access_token'])

    # set auth token in headers
    headers = {'Authorization': 'BEARER {}'.format(auth)}

    # note: this probably isn't really necessary but it doesn't hurt (all the sites times we are scraping are in EST)
    now = get_current_time_for_timezone("US/Eastern")

    # get ending timeframe for scraping dates - 190 days out
    until = now + SCRAPE_TIMEFRAME

    for filter_type in FILTER_TYPES:
        filter_url_query_attr = '&filters={}'.format(filter_type)

        scrape_date = now

        while scrape_date <= until:
            url = urljoin(SCRAPE_BASE_URL, '{}{}&date={}'.format(SCRAPE_BASE_URL_QUERY_STRING, filter_url_query_attr, scrape_date.strftime("%Y-%m-%d")))
            yield Request(url, headers=headers, callback=self.parse_ride_times, errback=self.error_handler)

            scrape_date += timedelta(days=1)

def parse_ride_times(self, response):
    # parse json data
    data = json.loads(response.body)

    for index, ride_details in enumerate(data['results']):

        if 'schedule' not in ride_details:
            continue

        ride_schedule = ride_details['schedule']

        # create item...

            yield item

Tags: inselfauthjsonformaturlfordata
1条回答
网友
1楼 · 发布于 2024-04-26 14:26:59

我能弄明白。为了在令牌过期时在头中设置一个新的授权令牌,我不得不重写Request对象。我把令牌作为一个全局变量。在

# override Request object in order to set new authorization token into the header when the token expires        
authorization_token = None

class AuthTokenRequest(Request):
    @property
    def headers(self):
        global authorization_token
        return Headers({'Authorization': 'BEARER {}'.format(authorization_token)}, encoding=self.encoding)

    @headers.setter
    def headers(self, value):
        pass

然后在while循环中的请求中使用重写的请求,其中包括一个errback函数error_handler,请求失败时调用该函数。error_handler函数获取一个新令牌,重置全局令牌变量,然后使用新令牌重新提交请求。在同一个请求中,dont_filter参数被设置为False,因此可以重新处理失败的请求。在

又创建了两个函数。创建了一个名为handle_auth的函数,最初在全局变量中设置令牌。另一个是start_first_run,它调用handle_auth并返回request_ride_times函数。这在start_requests请求中被调用。在

^{pr2}$

相关问题 更多 >