使用 python 抓取网站时获取最大页码
Getting max pagenumber when scraping website with python
我是 python 的新手,必须在网站上抓取大学课程的一些数据:
我能够得到我需要的信息。问题是每个条目(页、月、年)都需要它。
每个月的页数不同。有什么方法可以提取最大页码以便我可以存储它并将其用于循环吗?
如有任何帮助,我将不胜感激。谢谢!
For 循环很好,但您不能总是使用它们。在这种情况下,我会重复点击 'next page' 按钮中的 link 直到没有这样的按钮。像这样:
url = <first page>
while True:
# extract data
if <there is a next page button>:
url = <href of the button>
else:
break
这将获取您的所有页面,为每个页面生成一个 BeautifulSoup 对象,下一页的 link 位于带有 class 的锚标记中转发:
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)
我是 python 的新手,必须在网站上抓取大学课程的一些数据:
我能够得到我需要的信息。问题是每个条目(页、月、年)都需要它。
每个月的页数不同。有什么方法可以提取最大页码以便我可以存储它并将其用于循环吗?
如有任何帮助,我将不胜感激。谢谢!
For 循环很好,但您不能总是使用它们。在这种情况下,我会重复点击 'next page' 按钮中的 link 直到没有这样的按钮。像这样:
url = <first page>
while True:
# extract data
if <there is a next page button>:
url = <href of the button>
else:
break
这将获取您的所有页面,为每个页面生成一个 BeautifulSoup 对象,下一页的 link 位于带有 class 的锚标记中转发:
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)