要解决这个问题,你可以使用条件判断来检查链接是否有效。以下是一个示例代码:
from bs4 import BeautifulSoup
import requests
# 有效链接的列表
valid_links = ['http://example.com/page1', 'http://example.com/page2']
# 遍历链接
for link in valid_links:
# 发送请求获取页面内容
response = requests.get(link)
# 创建BeautifulSoup对象
soup = BeautifulSoup(response.text, 'html.parser')
# 使用条件判断来检查链接是否有效
if soup.find('div', class_='content'):
# 执行你的操作
print(f"{link} 是有效链接")
# 进行其他操作...
else:
print(f"{link} 是无效链接")
在上面的示例代码中,我们首先定义了一个有效链接的列表 你可以根据自己的需求进行修改和扩展这个示例代码。valid_links
。然后,我们遍历每个链接并发送请求来获取页面内容。接下来,我们使用 BeautifulSoup
来解析页面内容并使用 find()
方法查找特定的元素,这里是一个具有 class
属性为 'content'
的 相关内容