Python爬取Google搜索结果时标题主URL配对及循环重复问题求解
问题根因
- 现有代码使用双层嵌套循环,导致每个链接都会和所有h3标题匹配一次,自然出现匹配错位、输出重复的问题
- 不需要创建两个BeautifulSoup对象解析响应,同一个对象可同时提取标题和对应链接
- 谷歌搜索结果的标题和对应链接都包含在同一个父级元素内,直接遍历父级元素就能实现一一匹配
修正后的代码
import requests from bs4 import BeautifulSoup query = "data science" search = query.replace(' ', '+') results = 10 url = f"https://www.google.com/search?q={search}&num={results}" # 增加请求头避免被谷歌识别为爬虫拦截 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" } requests_results = requests.get(url, headers=headers) soup = BeautifulSoup(requests_results.content, "html.parser") # 遍历每个搜索结果的公共父容器 search_items = soup.find_all('div', class_='yuRUbf') count = 0 for item in search_items: if count >= results: break # 取当前结果对应的标题 title_tag = item.find('h3') if not title_tag: continue title = title_tag.get_text() # 取当前结果对应的链接 link_tag = item.find('a') if not link_tag: continue link_href = link_tag.get('href') if "url?q=" in link_href and not "webcache" in link_href: real_url = link_href.split("?q=")[1].split("&sa=U")[0] print(title) print(real_url) print("---------") count += 1
改动说明
- 新增了
User-Agent请求头,避免谷歌识别为爬虫直接拦截请求 - 去掉了双层嵌套循环,改为直接遍历谷歌搜索结果的公共父容器,每个父容器下只有1个标题和1个对应链接,从根源解决匹配错位问题
- 加了数量控制逻辑,拿到指定条数结果后直接终止循环,不会多输出内容
- 合并了两个重复创建的BeautifulSoup对象,减少冗余代码
内容的提问来源于stack exchange,提问作者HStoltz
相关产品推荐
相关产品推荐

