如何遵循302重定向,同时仍然获取页面信息时,使用Scrapy?

2024-09-26 18:05:01 发布

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

一直在努力绕过302重定向。首先,我的scraper的这个特殊部分的重点是获得下一页索引,这样我就可以翻页了。这个站点没有直接的url,所以我不能直接转到下一个或任何地方;为了继续使用parse_details函数来获取实际数据,我必须遍历每个页面并模拟请求。在

这对我来说都是新鲜事,所以我一定要先试试我能找到的任何东西。我尝试过各种设置(“REDIRECT_ENABLED”:False,改变handle_httpstatus_list,等等),但没有一个能让我通过这个过程。目前我试图跟踪重定向的位置,但这也不起作用。 下面是我尝试遵循的一个潜在解决方案的示例。在

try:
    print('Current page index: ', page_index)
except: # Will be thrown if page_index wasnt found due to redirection.
    if response.status in (302,) and 'Location' in response.headers:
        location = to_native_str(response.headers['location'].decode('latin1'))
         yield scrapy.Request(response.urljoin(location), method='POST', callback=self.parse)

代码,没有详细的解析等,如下所示:

^{2}$

或者,解决方案可能是以不同的方式跟踪分页,而不是发出所有这些请求? 原始链接是

https://m.tennislink.usta.com/TournamentSearch/searchresults.aspx?typeofsubmit=&action=2&keywords=&tournamentid=&sectiondistrict=&city=&state=&zip=&month=0&startdate=&enddate=&day=&year=2019&division=G16&category=28&surface=&onlineentry=&drawssheets=&usertime=&sanctioned=-1&agegroup=Y&searchradius=-1

如果有人能帮忙。在


Tags: toin重点indexif站点parseresponse
1条回答
网友
1楼 · 发布于 2024-09-26 18:05:01

您不必遵循302个请求,而是可以执行POST请求并接收页面的详细信息。以下代码打印前5页中的数据:

import requests
from bs4 import BeautifulSoup 

url = 'https://m.tennislink.usta.com/TournamentSearch/searchresults.aspx'

pages=5

for i in range(pages):

    params={'year':'2019','division':'G16','month':'0','searchradius':'-1'}
    payload={'__EVENTTARGET': 'dgTournaments:_ctl1:_ctl'+str(i)}

    res= requests.post(url,params=params,data=payload)
    soup = BeautifulSoup(res.content,'lxml')

    table=soup.find('table',id='ctl00_mainContent_dgTournaments')

    #pretty print the table contents
    for row in table.find_all('tr'):
        for column in row.find_all('td'):
            text = ', '.join(x.strip() for x in column.text.split('\n') if x.strip()).strip()
            print(text)
        print('-'*10)

相关问题 更多 >

    热门问题