要解决BeautifulSoup循环只提取第一页的数据的问题,你可以使用循环来迭代多个页面,并在每个页面上使用BeautifulSoup来提取数据。以下是一个示例代码:
import requests
from bs4 import BeautifulSoup
# 定义要爬取的页面链接列表
urls = ['https://example.com/page1', 'https://example.com/page2', 'https://example.com/page3']
# 循环迭代页面链接列表
for url in urls:
# 发送请求获取页面内容
response = requests.get(url)
# 使用BeautifulSoup解析页面内容
soup = BeautifulSoup(response.text, 'html.parser')
# 提取数据的代码
# 例如,提取页面中的所有标题
titles = soup.find_all('h1')
for title in titles:
print(title.text)
在上面的示例中,我们首先定义了要爬取的页面链接列表 urls
,然后使用循环迭代每个页面的链接。在循环中,我们发送请求获取页面内容,并使用BeautifulSoup解析页面内容。然后,我们可以根据需要编写相应的代码来提取想要的数据。在这个示例中,我们使用find_all()
方法找到页面中的所有标签,并使用
title.text
提取其文本内容。
你可以根据你要爬取的网站的具体结构和需要提取的数据进行适当的修改和调整。