要自动在网络上抓取网址并保存到数据库,需要编写一个自动化的网络爬虫程序。这个程序可以定期扫描指定的网站,并将其中的网址提取出来保存到数据库中。下面是一个简单的示例程序,该程序可以每天定期抓取指定网站中的所有链接,并将其保存到数据库中:
import requests
from bs4 import BeautifulSoup
import sqlite3
import datetime
import time
# 连接到数据库
conn = sqlite3.connect('links.db')
c = conn.cursor()
# 创建链接表格
c.execute('''CREATE TABLE IF NOT EXISTS links
(id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT,
date TEXT)''')
# 设置定时任务,每天抓取一次链接
while True:
# 发送 HTTP 请求,获取网页内容
url = 'https://www.example.com/'
response = requests.get(url)
# 使用 BeautifulSoup 解析网页内容,提取所有链接
soup = BeautifulSoup(response.text, 'html.parser')
links = []
for link in soup.find_all('a'):
link_url = link.get('href')
if link_url.startswith('http'):
links.append(link_url)
# 将提取的链接保存到数据库中
date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
for link in links:
c.execute("INSERT INTO links (url, date) VALUES (?, ?)", (link, date))
conn.commit()
# 等待一天
time.sleep(24*60*60)
,这个示例程序只是一个简单的演示,实际情况中需要根据具体的需求进行修改和优化。例如,需要考虑如何处理重复的链接、如何过滤掉无用的链接等问题。同时,需要注意遵守网站的使用协议,不要对网站造成过大的负担和影响。