这可能是由于变量在循环中被多次赋值而导致的。为了解决这个问题,可以使用列表来保存抓取的文本,然后使用join()函数将它们连接起来。例如:
import requests
from bs4 import BeautifulSoup
texts = []
# 循环抓取多个页面
for page in range(1, 10):
url = f"https://example.com/page/{page}"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
text = soup.find("div", {"class": "article"}).get_text()
texts.append(text)
# 将所有文本连接起来
all_text = "".join(texts)
print(all_text)
这样,所有的抓取文本将会被保存在texts列表中,并最终使用join()函数将它们合并成一个字符串,以便于后续的处理。