You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium循环打开URL时校验missing_amount并解决数据库重复插入及数据未写入问题

解决你的Selenium与数据库操作问题

一、确保missing_amount值存在于网页内容后再追加数据

你当前的逻辑是先爬取所有URL的内容到icl_dollar_amount_l和body_l,再和missing_amount做匹配,但这种方式容易出现索引不匹配、检查不严谨的问题。更可靠的做法是在打开每个URL时,直接检查当前页面是否包含目标缺失金额,确认存在后再提取并追加数据:

修改后的爬取逻辑

file_total_l = []
# 转成集合提升查找效率,避免重复遍历列表
missing_amount_set = set(missing_amount)

for link in url_list:
    print(link)
    options = Options()
    browser = webdriver.Chrome(options=options, executable_path=r'\\test\user$\test\Documents\driver\chromedriver.exe')
    try:
        browser.get(link)
        body = browser.find_element_by_xpath("//*[contains(text(), 'Total:')]").text
        # 提取当前页面的金额
        current_amount = re.findall('(?:[\£\$\€]{1}[,\d]+.?\d*)', body)[0].split('$', 1)[1]
        
        # 精确检查当前页面金额是否在missing_amount中
        if current_amount in missing_amount_set:
            file_total_l.append(current_amount)
    finally:
        browser.quit()  # 确保每次爬取后关闭浏览器,避免资源泄漏

如果只需要检查页面内容中包含该金额字符串(而非精确匹配),可以把判断逻辑改成:

has_missing = any(amount in body for amount in missing_amount_set)
if has_missing:
    # 提取并追加金额

二、解决数据库重复插入与165,757.06未插入问题

1. 避免重复插入数据库

每次运行脚本前,先查询数据库中已存在的file_total值,只插入不在已有集合中的数据:

# 查询数据库中已有的金额值,去重后存为集合
existing_query = "SELECT DISTINCT your_file_total_column FROM your_table_name"
sql_server_cursor.execute(existing_query)
existing_totals = {row[0] for row in sql_server_cursor.fetchall()}

# 仅插入新数据
for total in file_total_l:
    if total not in existing_totals:
        # 推荐用参数化查询避免SQL注入
        insert_query = "INSERT INTO your_table_name (file_total) VALUES (?)"
        sql_server_cursor.execute(insert_query, (total,))

# 记得提交事务,否则数据不会写入数据库
sql_server.commit()

2. 排查165,757.06未插入的问题

从你的打印信息看,目标值确实存在于icl_dollar_amount_l中,但未插入数据库,大概率是以下原因:

  • 索引不匹配:你当前用for i in range(len(missing_amount))循环,但若body_l/icl_dollar_amount_l的长度和missing_amount不一致,会导致取错对应页面的金额。比如missing_amount只有1个元素,body_l有3个,i=0时取的是第一个页面的金额627,418.07,而非目标值。
  • 格式隐形差异:检查两个列表中的值是否有隐藏空格、小数点位数差异(比如165,757.06和165,757.060)。可以统一转成浮点数比较:
    def amount_to_float(amount_str):
        return float(amount_str.replace(',', ''))
    
    # 比较时用浮点数判断
    if amount_to_float(missing_amount[i]) == amount_to_float(icl_dollar_amount_l[i]):
        # 执行后续逻辑
    
  • 事务未提交:确认数据库操作后是否执行了sql_server.commit(),否则数据不会持久化到数据库。

三、优化后的完整流程建议

  1. 先从数据库获取missing_amount列表
  2. 遍历URL时,只提取包含missing_amount值的页面金额到file_total_l
  3. 查询数据库已有金额,去重后插入新数据

这个流程既能满足"追加前确保missing_amount存在"的核心需求,又能解决重复插入和目标值未写入的问题。

内容的提问来源于stack exchange,提问作者python2134

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:27:39