请协助实现:检查CSV中final link无匹配时再追加写入功能
完善后的Python爬虫代码(实现CSV链接去重追加)
原代码存在的问题
- 未读取已有的CSV链接,
product_urls初始为空,无法实现去重逻辑 - 变量名冲突:外层循环的
i和内层遍历product_block的i重复,会导致循环逻辑混乱 soup.select用法错误:该方法需传入CSS选择器字符串,而非分离的class_参数writerow传参错误:直接传入字符串会被拆分为单个字符列,需传入列表格式- 提前关闭文件:
with语句会自动管理文件关闭,循环内手动关闭会导致后续写入失败
修正后的代码
import csv import requests from bs4 import BeautifulSoup # 先读取已存在的链接,存入集合(查询效率比列表高) product_urls = set() csv_file = 'plaid.csv' try: with open(csv_file, 'r', newline='', encoding='utf-8') as f: reader = csv.reader(f) # 跳过表头(如果你的CSV有表头的话,没有就删掉这行) next(reader) for row in reader: if row: # 跳过空行 product_urls.add(row[0]) except FileNotFoundError: # 文件不存在时,初始化空集合 pass # 爬取页面(这里示例爬取第0页,可根据需求修改范围) for page_num in range(0, 1): url = f'https://plaidonline.com/products?closeout=True&page={page_num}' r = requests.get(url=url, headers=headers).content soup = BeautifulSoup(r, 'lxml') # 修正CSS选择器写法 product_block = soup.select('div.col-xs-12.col-md-8.col-lg-9') for block in product_block: # 找到所有tile-link链接 href_list = block.find_all(class_='tile-link', href=True) for link in href_list: relative_link = link.get('href') final_link = 'https://plaidonline.com' + relative_link # 链接不存在于已有集合时,写入CSV并添加到集合 if final_link not in product_urls: product_urls.add(final_link) with open(csv_file, 'a', newline='', encoding='utf-8') as f_object: writer_object = csv.writer(f_object) # 如果是第一次写入(文件刚创建),可以先写表头 # if len(product_urls) == 1: # writer_object.writerow(['Product Link']) writer_object.writerow([final_link])
关键优化点
- 使用集合存储已存在的链接,查询时间复杂度从O(n)降到O(1),提升去重效率
- 分离文件读取和写入逻辑,先加载所有已有链接再进行爬取判断
- 修正了BeautifulSoup选择器和CSV写入的语法错误
- 处理了文件不存在的异常情况,保证代码鲁棒性
内容的提问来源于stack exchange,提问作者Акрам Джураев
相关产品推荐
相关产品推荐

