【问题标题】:Scraping multiple pages in Beautiful Soup在 Beautiful Soup 中抓取多个页面
【发布时间】:2021-08-22 13:52:40
【问题描述】:

我正在尝试抓取该网站中的所有页面:https://www.edison.k12.nj.us/directory?const_page=1&。我想我可以通过将数字 1 替换为 2、3、4 等等来进入下一页。但是,情况并非如此,因为当我检查标签的 href 属性时,它似乎没有链接到新页面。在这种情况下,我该如何抓取多个页面?非常感谢!

page = 1
df_list = []
df = None
while(page < 240):
    url = 'https://www.edison.k12.nj.us/directory?const_page='+str(page)+'&amp;'
    # gets back the beautiful soup object
    bs = create_beautiful(url)

    #calls the extract_data to get necessary data()
    df2 = extract_data(bs)
    if page == 1:
        df = df2
        
    else:
        df_list.append(df2)
        

    page+=1

count = 1
for df2 in df_list:
    df.append(df2 , ignore_index = True)
    count+=1

to_csv_and_excel(df, 'edison_township_public')

【问题讨论】:

    标签: python-3.x beautifulsoup


    【解决方案1】:

    您可以在开发工具 -> 网络 -> Fetch/XHR 选项卡中查看是否有任何请求正在从服务器发送或发送到服务器。尝试单击下一页,您将在 headers 选项卡中看到此链接:

    https://www.edison.k12.nj.us/fs/elements/59?const_page=1&is_draft=false&is_load_more=true&parent_id=59&_=1629643598511
    

    您可以尝试在range() 循环中做一个非常基本的for 并将const_page={VALUE}parent_id=59&amp;_=162964359851{VALUE} 替换为循环值。

    注意:它很慢,如果需要,需要用更快的解决方案替换。

    for index in range(1, 240):
    
      params = {
        'const_page': index, 
        'is_draft': 'false',
        'is_load_more': 'true',
        'parent_id': '59',
        '_': f'162964359851{index}' # only LAST number changing on each page. Same as const_page number.
        
      }
      
      html = requests.get(f"https://www.edison.k12.nj.us/fs/elements/59", params=params)
      soup = BeautifulSoup(html.text, 'lxml')
    
      title = soup.select_one('.fsConstituentProfileLink').text
    
    --------
    '''
    Donna Abatemarco 
    Irina Acha 
    Philip Adornato 
    Victoria Ajijedidun 
    Taylor Aljian 
    Kelly Amabile 
    Elizabeth Andrade 
    Deliane Antonio 
    Nicole Aravena 
    Pamela Aurilio 
    Aimee Baer 
    Sharmila Balaji 
    Meghan Banach 
    ... more names
    '''
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-25
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 2020-04-28
      • 2017-03-30
      • 2019-11-14
      • 1970-01-01
      相关资源
      最近更新 更多