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

Python判断URL是否包含排除站点列表元素时TypeError问题咨询

错误原因

in关键字的左右操作数逻辑有误:

  • 单个排除站点时,你判断的是单个排除字符串是否存在于链接字符串,语法符合要求
  • 改为元组后,if donts in thingy是尝试将整个元组作为整体判断是否存在于字符串中,二者类型不匹配,因此抛出 TypeError。你实际需要实现的逻辑是判断元组内任意一个排除站点字符串是否存在于当前链接中。

修复方案

将原判断行替换为any()遍历判断即可,修改后完整代码如下:

import requests 
from bs4 import BeautifulSoup
from lxml import html, etree
import sys
import re

url = "http://stackoverflow.com"

donts = ('stackoverflow.com', 'stackexchange.com')

r = requests.get(url, timeout=6, verify=True)

soup = BeautifulSoup(r.content, 'html.parser')

for link in soup.select('a[href*="http"]'):
    thingy = str(link.get('href'))
    # 遍历所有排除站点,只要有一个匹配就跳过
    if any(dont in thingy for dont in donts):
        pass
    else:
        print(thingy)

补充说明

如果需要严格匹配域名、避免误伤路径中带排除关键词的链接(比如xxx.com/stackoverflow.com/xxx这类场景),可以先提取链接的域名再和排除列表做全等判断,实现更精准的过滤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:18:03