【问题标题】:BeautifulSoup looping through urlsBeautifulSoup 通过 url 循环
【发布时间】:2015-03-01 09:59:54
【问题描述】:

我正在尝试收获一些国际象棋游戏,并在此处的一些帮助下完成了基础知识。主要功能如下所示:

import requests
import urllib2
from bs4 import BeautifulSoup

r = requests.get(userurl)
soup = BeautifulSoup(r.content)
gameids= []
for link in soup.select('a[href^=/livechess/game?id=]'):
    gameid = link['href'].split("?id=")[1]
    gameids.append(int(gameid))
    return gameids

基本上发生的情况是我转到特定用户的 URL,例如 http://www.chess.com/home/game_archive?sortby=&show=live&member=Hikaru,grab html 并抓取游戏 ID。这适用于一页。 但是有些用户玩了很多游戏,由于每页只显示 50 个游戏,他们的游戏被列在多个页面上。例如 http://www.chess.com/home/game_archive?sortby=&show=live&member=Hikaru&page=2(或 3/4/5 等) 这就是我卡住的地方。如何循环浏览页面并获取 ID?

【问题讨论】:

    标签: python html web-scraping beautifulsoup html-parsing


    【解决方案1】:

    通过无限循环跟随分页并点击“Next”链接直到找不到。

    换句话说,来自:

    跟随“下一步”链接直到:

    工作代码:

    from urlparse import urljoin
    
    import requests
    from bs4 import BeautifulSoup
    
    base_url = 'http://www.chess.com/'
    game_ids = []
    
    next_page = 'http://www.chess.com/home/game_archive?sortby=&show=live&member=Hikaru'
    while True:
        soup = BeautifulSoup(requests.get(next_page).content)
    
        # collect the game ids
        for link in soup.select('a[href^=/livechess/game?id=]'):
            gameid = link['href'].split("?id=")[1]
            game_ids.append(int(gameid))
    
        try:
            next_page = urljoin(base_url, soup.select('ul.pagination li.next-on a')[0].get('href'))
        except IndexError:
            break  # exiting the loop if "Next" link not found
    
    print game_ids
    

    对于您提供的 URL (Hikaru GM),它会为您打印一个包含所有页面的 224 个游戏 ID 的列表。

    【讨论】:

    • 完美运行,正是我所需要的。非常感谢 alecxe:)!
    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 2020-01-27
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    相关资源
    最近更新 更多