【问题标题】:Getting max pagenumber when scraping website with python使用python抓取网站时获取最大页码
【发布时间】:2016-09-04 07:39:51
【问题描述】:

我对 python 很陌生,必须从网站上抓取一些大学课程的数据:

Xrel

我能够获得我需要的信息。问题是我每个条目(页、月、年)都需要它。

每个月的页面数量都不同。有什么方法可以提取最大页码,以便我可以存储它并将其用于循环?

我将不胜感激。谢谢!

【问题讨论】:

    标签: python beautifulsoup screen-scraping bs4


    【解决方案1】:

    For 循环很好,但你不能总是使用它们。在这种情况下,我会反复点击“下一页”按钮中的链接,直到没有这样的按钮。像这样的:

    url = <first page>
    while True:
        # extract data
        if <there is a next page button>:
            url = <href of the button>
        else:
            break
    

    【讨论】:

      【解决方案2】:

      这将获取您的所有页面,为每个页面生成一个 BeautifulSoup 对象,指向下一页的链接位于带有 forward 类的锚标记中:

      import requests
      from urlparse import urljoin
      
      
      def get_pages(base, url):
          soup = BeautifulSoup(requests.get(url).content)
          yield soup
          next_page = soup.select_one("a.forward")
          for page in iter(lambda: next_page, None):
              soup = BeautifulSoup(requests.get(urljoin(base, page["href"])).content)
              yield soup
              next_page = soup.select_one("a.forward")
      
      
      
      for soup in get_pages("https://www.xrel.to/", "https://www.xrel.to/games-release-list.html?archive=2016-01"):
          print(soup)
      

      【讨论】:

      • 也感谢您。但我已经在自己的解决方案中实现了 Alex 的想法。我在前锋班上做到了这一点
      • @Sannin,另一方面,你真的应该检查你是否正确地恢复了源并捕获连接错误,仅仅因为你没有找到按钮并不一定意味着它是因为你到达最后一页
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 2020-03-09
      相关资源
      最近更新 更多