如何用BeautifulSoup爬取公司名称地址对应电话号码 解决链接返回None问题
爬虫脚本修复方案
现有代码问题梳理
- 链接提取逻辑错误:
lis.find('href', class_ ="col1")写法不符合BeautifulSoup语法,href是a标签的属性而非标签名,无法正确获取详情页地址 - 无详情页请求逻辑:未对提取到的详情页链接发起访问,自然无法获取电话号码
- 变量名冲突:循环变量
page和requests请求返回的变量重名,容易引发未知错误 - 数据存储逻辑错误:
info变量在循环中被反复覆盖,且打印语句放在循环外,最终只会输出最后一条数据 - 缺少反爬规避:没有加请求头,很容易被目标站点拦截,返回异常内容
修复后可运行代码
import requests from bs4 import BeautifulSoup import time # 加请求头模拟浏览器访问,避免被反爬拦截 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" } # 存储所有抓取到的信息 all_company_info = [] for page_num in range(1, 65): url = f"https://www.expansion.com/empresas-de/ganaderia/granjas-en-general/{page_num}.html" try: # 请求列表页 list_resp = requests.get(url, headers=headers, timeout=10) list_resp.encoding = list_resp.apparent_encoding list_soup = BeautifulSoup(list_resp.content, "html.parser") lists = list_soup.select("div#simulacion_tabla ul") for lis in lists: # 提取基础信息 title = lis.find('li', class_="col1").text.strip() location = lis.find('li', class_="col2").text.strip() province = lis.find('li', class_="col3").text.strip() # 正确提取详情页链接 col1_a = lis.find('li', class_="col1").find('a') if not col1_a: link = "无详情页" phone = "无" else: link = col1_a.get("href") # 补全相对路径 if not link.startswith("http"): link = f"https://www.expansion.com{link}" # 请求详情页拿手机号 try: # 加延迟避免请求过快被封 time.sleep(0.5) detail_resp = requests.get(link, headers=headers, timeout=10) detail_resp.encoding = detail_resp.apparent_encoding detail_soup = BeautifulSoup(detail_resp.content, "html.parser") # 选择器可根据实际详情页结构调整,当前是该站点通用的电话节点类名 phone_node = detail_soup.find("span", class_="telefono") phone = phone_node.text.strip() if phone_node else "未公示" except Exception as e: phone = "详情页请求失败" # 组装数据存入总列表 company_info = [title, location, province, link, phone] all_company_info.append(company_info) print(f"已抓取:{title}") except Exception as e: print(f"第{page_num}页请求失败:{str(e)}") continue # 打印所有结果,也可以自行写入csv文件 for item in all_company_info: print(item)
googlesearch库适用性说明
可以实现但不推荐使用。当前目标站点列表页已经直接提供了所有公司的详情页入口,直接抓取的链路最短、效率最高。如果使用googlesearch实现,需要把每个公司名称作为搜索词发起请求,再从搜索结果中匹配正确的详情页链接,不仅会大幅增加抓取耗时,还容易触发谷歌的反爬机制,额外增加使用成本,只有当站点列表页未提供详情页链接时才适合使用该方案。
内容的提问来源于stack exchange,提问作者Nick Gordon
相关产品推荐
相关产品推荐

