在网页中不止一页内容时,使用BeautifulSoup去抓取下一页内容可能会出现问题。这时需要结合其他库或者使用网页请求获取下一页的内容。
具体解决方法可以参考以下代码示例:
import requests
from bs4 import BeautifulSoup
# 首先,使用requests获取第一页的内容
url = "https://example.com/page-1"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# 然后,找到下一页的链接
next_page_link = soup.find("a", {"class": "next-page-link"}).get("href")
# 最后,使用requests获取下一页的内容并用BeautifulSoup解析
next_page_response = requests.get(next_page_link)
next_page_soup = BeautifulSoup(next_page_response.content, 'html.parser')
在这个例子中,我们通过requests获取了第一页的内容,然后使用BeautifulSoup解析。接着,找到下一页的链接,并使用requests获取下一页的内容,最后用BeautifulSoup解析获取到下一页的内容。