如何用Python实现多网站多词查找及部分匹配?解决代码报错
多网站关键词查询优化:支持多词+模糊匹配
问题A:支持多词查询
原代码仅适配单个关键词,改成多词列表/元组时报错,核心原因是lambda判断逻辑只针对单个字符串。修改思路:
- 将查询词定义为列表(比如
the_words = ['UKCA', 'CA', 'PS24']) - 用
any()函数替换原单条件判断,检查文本是否包含任意一个关键词
问题B:实现类似SQL LIKE的模糊匹配
要匹配同一词根的变体(比如certification/certified/certificate),有两种实用方案:
- 词根匹配:直接检查文本中是否包含核心词根(比如
'certif'),简单高效 - 正则匹配:用正则表达式精准覆盖所有目标变体,灵活性更强
修改后的完整代码
# 统计多网站中关键词/词根的出现情况 import requests from bs4 import BeautifulSoup import re url_list = ["http://www.a-w-s.co.uk/","http://www.albanywindows.co.uk","http://www.aimwindows.co.uk"] # 多词查询配置(替换成你的目标关键词列表) the_words = ['UKCA', 'CA', 'PS24'] # 模糊匹配配置:二选一即可 # 方案1:词根匹配(简单直接) target_root = 'certif' # 方案2:正则匹配(精准覆盖变体,忽略大小写) pattern = re.compile(r'certif(?:y|ied|icate|ication)', re.IGNORECASE) total_matches = [] for url in url_list: try: r = requests.get(url, allow_redirects=False, timeout=10) r.raise_for_status() # 捕获请求错误(404/超时等) soup = BeautifulSoup(r.content.lower(), 'lxml') # 启用多词查询:匹配任意一个关键词 # words = soup.find_all(text=lambda text: text and any(word.lower() in text for word in the_words)) # 启用模糊匹配:选其中一种即可 # 方案1:词根匹配 words = soup.find_all(text=lambda text: text and target_root in text) # 方案2:正则匹配 # words = soup.find_all(text=lambda text: text and pattern.search(text)) count = len(words) cleaned_matches = [ele.strip() for ele in words] total_matches.extend(cleaned_matches) print(f'\nUrl: {url}') print(f'匹配到 {count} 条内容') print('匹配内容:', cleaned_matches) except requests.exceptions.RequestException as e: print(f'\nUrl: {url} 请求失败:{str(e)}') total_count = len(total_matches) print(f'\n所有网站共匹配到 {total_count} 条内容') # print('所有匹配内容:', total_matches)
关键改动说明
- 多词查询:通过
any(word.lower() in text for word in the_words)遍历关键词列表,实现“或”逻辑匹配 - 模糊匹配:
- 词根匹配:利用词根共性覆盖所有变体,无需复杂规则
- 正则匹配:预编译正则表达式,
re.IGNORECASE忽略大小写,非捕获组(?:...)减少冗余计算
- 异常处理:增加请求错误捕获,避免100+网站批量查询时中途崩溃
内容的提问来源于stack exchange,提问作者nihility24
相关产品推荐
相关产品推荐

