以下是一个示例代码,演示如何通过提前检查 JSON 或 CSV 文件中的 URL 来避免重复抓取博客:
import json
import csv
import requests
def check_duplicate_urls(urls, target_url):
return target_url in urls
def save_url_to_file(url, file_path):
with open(file_path, 'a') as file:
file.write(url + '\n')
def read_urls_from_json(json_file):
with open(json_file, 'r') as file:
data = json.load(file)
return data['urls']
def read_urls_from_csv(csv_file):
urls = []
with open(csv_file, 'r') as file:
reader = csv.reader(file)
for row in reader:
urls.extend(row)
return urls
def crawl_blog(url, json_file, csv_file):
json_urls = read_urls_from_json(json_file)
csv_urls = read_urls_from_csv(csv_file)
if check_duplicate_urls(json_urls + csv_urls, url):
print(f"URL {url} has already been crawled.")
return
# 进行博客抓取的代码
response = requests.get(url)
# 处理抓取到的博客数据
# 将已抓取的 URL 保存到 JSON 文件
json_urls.append(url)
with open(json_file, 'w') as file:
json.dump({'urls': json_urls}, file)
# 将已抓取的 URL 保存到 CSV 文件
save_url_to_file(url, csv_file)
# 示例用法
crawl_blog('https://example.com/blog1', 'urls.json', 'urls.csv')
crawl_blog('https://example.com/blog2', 'urls.json', 'urls.csv')
crawl_blog('https://example.com/blog1', 'urls.json', 'urls.csv') # 这次会被检测到重复
在上面的示例代码中,check_duplicate_urls
函数用于检查目标 URL 是否已经存在于已抓取的 URL 列表中。save_url_to_file
函数用于将已抓取的 URL 保存到文件中。
read_urls_from_json
和 read_urls_from_csv
函数分别用于从 JSON 文件和 CSV 文件中读取已抓取的 URL 列表。
crawl_blog
函数是一个示例的博客抓取函数。它首先读取已抓取的 URL 列表,然后使用 check_duplicate_urls
函数检查目标 URL 是否已经存在于列表中。如果存在,则打印出重复抓取的信息并退出。如果不存在,则进行博客抓取,并将已抓取的 URL 保存到 JSON 文件和 CSV 文件中。
上一篇:避免重复转换多个字符串为浮点数