用for循环爬取五个网站
时间: 2024-09-16 08:04:03 浏览: 47
在Python中,使用for循环结合requests库来爬取多个网站通常是通过列表存储目标URL,然后遍历这个列表执行请求。以下是一个简单的示例,假设我们有五个网站URL:
```python
import requests
# 假设这是你要抓取的五个网站URL
urls = ['http://example1.com', 'http://example2.com', 'http://example3.com', 'http://example4.com', 'http://example5.com']
for i, url in enumerate(urls):
try:
# 发送GET请求
response = requests.get(url)
# 确保请求成功(状态码200)
if response.status_code == 200:
print(f"正在爬取第{i+1}个网站:{url}")
# 这里可以添加解析网页内容的代码,比如BeautifulSoup或正则表达式
# response.text 或 response.json() 分别获取HTML文本或JSON数据
else:
print(f"访问 {url} 失败,状态码:{response.status_code}")
except requests.exceptions.RequestException as e:
print(f"遇到错误:{e}")
阅读全文
相关推荐


















