编写一个循环的网络爬虫可以按照以下步骤进行:
requests
和BeautifulSoup
。import requests
from bs4 import BeautifulSoup
def process_data(html):
# 使用BeautifulSoup解析html
soup = BeautifulSoup(html, 'html.parser')
# 提取所需的数据
# ...
# 保存数据到文件或数据库
# ...
def get_html(url):
# 发送HTTP请求
response = requests.get(url)
# 检查响应状态码
if response.status_code == 200:
# 获取网页内容
html = response.text
return html
else:
# 处理错误
return None
def main():
# 定义要爬取的网页链接列表
urls = ['https://example.com/page1', 'https://example.com/page2', 'https://example.com/page3']
for url in urls:
# 获取网页内容
html = get_html(url)
# 处理数据
process_data(html)
main
函数来启动爬虫。if __name__ == '__main__':
main()
请注意,上述代码仅为示例,实际的爬虫可能需要处理更复杂的网页结构、使用代理、处理动态网页等。此外,还应注意遵守网站的爬取规则和法律法规。