如何将搜索项/短代码对应的链接存储到列表或字典中?
解决短代码搜索链接的存储问题
嘿,我来帮你搞定这个需求!你想把每个短代码对应的Google搜索链接存起来,不管用列表还是字典都很简单,下面一步步给你说明:
方案思路
咱们用字典来存储最直观——直接把短代码作为键,它对应的所有搜索链接列表作为值,后续查询、导出都方便;如果偏好列表,也可以把每个短代码和链接列表打包成元组存入列表,灵活度也够。
修改后的完整代码
先补上原代码里缺失的模块导入,再添加核心的存储逻辑:
import pandas as pd import requests import time from tqdm import tqdm import numpy as np from googlesearch import search from requests.exceptions import HTTPError # 初始化存储字典:键=短代码,值=该短代码对应的搜索链接列表 results_dict = {} try: with open('Unknown.xlsx', "rb") as f: df = pd.read_excel(f) shortcode_list = df['Short Code'].tolist() except FileNotFoundError: print("找不到文件Unknown.xlsx,请检查路径是否正确!") exit() def stopwatch(sec): while sec: minn, sec = divmod(sec, 60) timeformat = '{:02d}:{:02d}'.format(minn, sec) print(timeformat, end='\r') time.sleep(1) sec -= 1 # 循环处理每个短代码 for shortcode in tqdm(shortcode_list): # 为当前短代码初始化空的链接列表 current_links = [] try: # 随机延迟,避免被Google反爬拦截 delay = np.random.choice(np.arange(1, 60, 1).tolist()) pause = np.random.choice(np.arange(2, 8, 1).tolist()) stopwatch(delay) # 构造搜索查询语句 query = f'text * to "{shortcode}"' url = f'https://www.google.com?q={query}' # 注意:这里的headers需要你自己定义,比如headers = {"User-Agent": "Mozilla/5.0..."} res = requests.get(url, headers=headers) print(f"\n当前查询: {query} | 请求状态: {res}") # 遍历搜索结果,收集所有链接 for k in search(query, tld="co.in", num=10, stop=10, pause=pause, country='US', user_agent=search.get_random_user_agent(), verify_ssl=True): print(k) current_links.append(k) # 把当前短代码的链接列表存入字典 results_dict[shortcode] = current_links except HTTPError as exception: if exception.code == 429: print(f"遇到429拦截:{exception}") print("等待8分钟后继续...") stopwatch(480) # 给被拦截的短代码存空列表,避免字典缺失键 results_dict[shortcode] = [] continue except Exception as e: print(f"处理短代码{shortcode}时出错:{e}") results_dict[shortcode] = [] continue # 打印存储结果的示例 print("\n=== 存储的搜索结果预览 ===") for sc, links in results_dict.items(): print(f"短代码 {sc}: 找到 {len(links)} 条链接") if links: print(f"前2条链接: {links[:2]}") # 要是想把结果导出到Excel,uncomment下面这行 # pd.DataFrame.from_dict(results_dict, orient='index').to_excel('ShortCode_Search_Results.xlsx')
关键修改点说明
- 新增存储结构:用
results_dict字典关联短代码和链接列表,每个短代码对应自己的搜索结果集合 - 链接收集逻辑:对每个短代码先创建空列表
current_links,遍历搜索结果时把链接逐个append进去,最后存入字典 - 异常兼容:遇到拦截或报错时,给对应短代码存入空列表,保证字典结构完整,不会出现键缺失
- 补全依赖:添加了原代码遗漏的模块导入,避免运行报错
列表存储的替代方案
如果更想用列表存储,只需要把results_dict换成results_list = [],然后在收集完current_links后添加:
results_list.append( (shortcode, current_links) )
这样列表里的每个元素都是(短代码, 链接列表)的元组,后续遍历使用也很方便。
内容的提问来源于stack exchange,提问作者Mohamed Elgendy
相关产品推荐
相关产品推荐

