我们可以使用循环操作从列表中遍历每个URL,并在每个URL上执行BeautifulSoup对象的文本抓取方法。以下是一个示例代码,演示如何通过循环在BeautifulSoup中抓取多个文本字段。
import requests
from bs4 import BeautifulSoup
url_list = ['https://example.com/page1', 'https://example.com/page2', 'https://example.com/page3']
for url in url_list:
# 发送请求获取HTML
response = requests.get(url)
# 创建BeautifulSoup对象
soup = BeautifulSoup(response.content, 'html.parser')
# 使用soup对象的find和find_all方法定位需要抓取的文本
title = soup.find('h1', {'class': 'title'}).text
content = soup.find('div', {'class': 'content'}).text
# 输出抓取到的文本
print("URL: ", url)
print("Title: ", title)
print("Content: ", content)
在上面的代码中,我们首先定义了一个URL列表。然后我们使用for循环遍历每个URL,发送请求以获取HTML内容。我们使用BeautifulSoup对象定位需要抓取的文本。在这个例子中,我们抓取了一个标题和一个内容的文本字段。最后,我们在控制台输出抓取到的文本。