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

如何使用Python从主链接列表中移除指定子列表获取剩余URL

实现剩余URL计算的Python方案

核心逻辑说明

要实现balance_urls = 全部链接 - (含coupon的链接 + 含review的链接)的需求,直接用Python内置的集合运算即可高效完成,集合天然支持去重、并集、差集操作,不需要手动写遍历去重的逻辑。

修改步骤

1. 新增剩余URL计算逻辑

在原有代码计算完all_review的统计后,添加如下代码:

# 转集合做运算,自动去重
all_links_unique = set(all_links)
coupon_review_unique = set(all_coupon).union(set(all_review))
# 求差集得到剩余URL,转成列表方便后续处理
balance_urls = list(all_links_unique - coupon_review_unique)
balance_counter = len(balance_urls)

# 打印剩余URL统计
print('剩余URL数量:', balance_counter, ' 对应的链接:', balance_urls)
print()

2. 将剩余URL字段加入结果字典

修改原有product字典,补充剩余URL的相关字段:

product = {
    'All Links Counter': all_links_counter,
    'All Links': ', '.join(all_links),
    'coupon Counter': coupon_counter,
    'coupon Links': ', '.join(all_coupon),
    'review Counter': review_counter,
    'review Links': ', '.join(all_review),
    # 新增剩余URL统计字段
    '剩余URL数量': balance_counter,
    '剩余URL列表': ', '.join(balance_urls)
}

可选优化:减少页面遍历次数

原有代码三次遍历页面所有a标签分别统计三类链接,可以合并为一次遍历,提升运行效率:

# 替换原有三次遍历soup的逻辑,一次遍历收集所有需要的链接
all_links = []
all_coupon = []
all_review = []
for link in soup.find_all('a', href=True):
    current_link = link['href']
    all_links.append(current_link)
    if 'coupon' in current_link:
        all_coupon.append(current_link)
    if 'review' in current_link:
        all_review.append(current_link)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:15:03