用 Python 轻松抓取百度收录量:从原理到实战的全流程指南
**作为内容创作者,你是否经常好奇自己的文章在百度上的收录情况?掌握百度收录量不仅能直观反映内容的影响力,更是优化 SEO 策略的重要依据。今天就来教大家用 Python 实现百度收录量的自动化抓取,让数据驱动内容创作。
一、抓取原理与准备工作
1.1 百度收录量的查询逻辑
百度收录量本质上是通过特定语法在百度搜索结果中获取的统计数据。当我们在百度搜索框输入site:你的网址时,搜索结果页会显示该域名下被百度收录的网页数量。例如输入site:zhihu.com,就能看到知乎在百度的收录总量。这种查询方式基于百度的site指令,其工作原理是:百度搜索引擎会定期爬取互联网网页并建立索引,site指令相当于告诉百度 “只展示这个域名下的索引结果”,并返回收录数量。
1.2 技术栈准备
实现抓取需要以下 Python 库:
requests:用于发送 HTTP 请求获取网页内容
BeautifulSoup:解析 HTML 页面提取关键信息
re:正则表达式模块,用于处理复杂文本匹配
time:添加延时避免频繁请求
pandas:可选,用于数据存储和分析
安装命令:
pip install requests beautifulsoup4 pandas
二、核心代码实现
2.1 基础抓取函数
首先实现一个基础的百度收录量抓取函数:
import requestsfrom bs4 import BeautifulSoupimport reimport timeimport randomdef get_baidu_index(url, delay=3):"""获取指定网址的百度收录量url: 要查询的网址(如https://www.example.com)delay: 请求间隔时间(秒)"""# 处理网址格式,确保以http或https开头if not url.startswith(('http://', 'https://')):url = 'https://' + url# 构造查询URLquery_url = f'https://www.baidu.com/s?wd=site:{url}'# 设置请求头,模拟浏览器访问headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36','Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8','Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'}# 添加随机延时,避免被封IPtime.sleep(delay + random.uniform(0, 2))try:# 发送请求response = requests.get(query_url, headers=headers, timeout=10)response.raise_for_status() # 检查请求是否成功# 解析HTMLsoup = BeautifulSoup(response.text, 'html.parser')html_content = soup.prettify()# 提取收录量信息index_count = extract_index_count(html_content)return {'url': url,'index_count': index_count,'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),'status': 'success'}except requests.RequestException as e:print(f"请求出错: {e}")return {'url': url,'index_count': None,'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),'status': 'error','error_msg': str(e)}except Exception as e:print(f"处理出错: {e}")return {'url': url,'index_count': None,'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),'status': 'error','error_msg': str(e)}
2.2 解析收录量的关键函数
上面的代码中,extract_index_count函数是解析的核心:
def extract_index_count(html_content):"""从HTML内容中提取百度收录量"""# 百度搜索结果中收录量的常见正则模式patterns = [r'找到相关结果约(.*?)个',r'共找到(.*?)条相关结果',r'约(.*?)个网页符合']for pattern in patterns:match = re.search(pattern, html_content)if match:count_text = match.group(1).strip()# 处理数字格式,如"123,456"转换为123456count_text = count_text.replace(',', '')# 处理"123万"这样的格式if '万' in count_text:num = float(count_text.replace('万', '')) * 10000return int(num)# 处理"1.2亿"这样的格式elif '亿' in count_text:num = float(count_text.replace('亿', '')) * 100000000return int(num)# 纯数字格式elif count_text.isdigit():return int(count_text)else:print(f"无法解析的收录量格式: {count_text}")return None# 所有模式都未匹配print("未找到收录量信息")return None
2.3 批量查询与数据存储
实际应用中,我们通常需要批量查询多个网址的收录量并存储数据:
import pandas as pddef batch_query_urls(url_list, output_file=None, delay=3):"""批量查询多个网址的百度收录量"""results = []for url in url_list:print(f"正在查询: {url}")result = get_baidu_index(url, delay)results.append(result)# 显示进度print(f"查询完成: {url}, 收录量: {result.get('index_count', '未知')}")# 存储为DataFramedf = pd.DataFrame(results)# 保存到文件if output_file:if output_file.endswith('.csv'):df.to_csv(output_file, index=False, encoding='utf-8-sig')elif output_file.endswith(('.xlsx', '.xls')):df.to_excel(output_file, index=False)else:print(f"不支持的文件格式: {output_file}")return df# 使用示例if __name__ == "__main__":# 要查询的网址列表urls = ['https://www.zhihu.com','https://mp.weixin.qq.com','https://www.toutiao.com','https://blog.csdn.net']# 批量查询并保存结果result_df = batch_query_urls(urls, 'baidu_index_results.csv', delay=5)print("查询完成,结果已保存到baidu_index_results.csv")
三、进阶优化与反爬应对
3.1 代理 IP 池的实现
为避免频繁请求导致 IP 被封,建议使用代理 IP:
import randomdef get_proxy():"""获取代理IP(实际应用中应从代理IP服务获取)"""# 这里仅为示例,实际应从代理IP服务商获取可用代理proxy_list = ['http://127.0.0.1:8080','http://127.0.0.1:8081',# 添加更多代理IP]return random.choice(proxy_list)# 在get_baidu_index函数中使用代理proxy = get_proxy()response = requests.get(query_url, headers=headers, proxies={'http': proxy, 'https': proxy}, timeout=10)
3.2 验证码处理
当百度检测到异常请求时,可能会返回验证码页面。处理方法有两种:
3.2.1 Selenium 模拟浏览器
from selenium import webdriverfrom selenium.webdriver.chrome.options import Optionsdef get_baidu_index_with_selenium(url):"""使用Selenium模拟浏览器访问"""chrome_options = Options()# 无头模式(可选)# chrome_options.add_argument('--headless')chrome_options.add_argument('--disable-gpu')chrome_options.add_argument(f'user-agent={headers["User-Agent"]}')driver = webdriver.Chrome(options=chrome_options)try:driver.get(f'https://www.baidu.com/s?wd=site:{url}')# 等待页面加载time.sleep(5)# 如果出现验证码,需要人工处理print("请检查是否需要人工处理验证码")# 等待用户处理验证码input("处理完成后按Enter继续...")html_content = driver.page_sourceindex_count = extract_index_count(html_content)return {'url': url,'index_count': index_count,'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),'status': 'success'}finally:driver.quit()
3.2.2 验证码识别 API
对于自动化场景,可使用第三方验证码识别服务:
def recognize_captcha(image_path):"""调用第三方验证码识别API"""# 这里以打码平台为例,实际需根据具体API调整api_key = "你的API密钥"url = "https://api.example.com/recognize"with open(image_path, 'rb') as f:files = {'image': f}data = {'api_key': api_key}response = requests.post(url, files=files, data=data)return response.json().get('result', '')
四、实战案例:公众号收录量监控
4.1 公众号文章收录量统计
很多公众号运营者关心文章被百度收录的情况,可通过以下代码实现:
def get_wechat_article_index(article_url, delay=5):"""获取公众号文章的百度收录量"""# 公众号文章在百度的收录量查询return get_baidu_index(article_url, delay)# 监控多个公众号文章wechat_articles = ['https://mp.weixin.qq.com/s/abc123', # 文章1'https://mp.weixin.qq.com/s/def456', # 文章2# 添加更多文章链接]# 每天定时查询import scheduledef daily_monitor():"""每日定时监控"""print(f"开始每日收录量监控: {time.strftime('%Y-%m-%d')}")result_df = batch_query_urls(wechat_articles, f"wechat_index_{time.strftime('%Y%m%d')}.csv")print("今日监控完成")# 设置每天9点执行监控schedule.every().day.at("09:00").do(daily_monitor)# 持续运行while True:schedule.run_pending()time.sleep(60)
4.2 数据可视化分析
使用matplotlib或pyecharts对收录量数据进行可视化:
import matplotlib.pyplot as pltfrom pyecharts import options as optsfrom pyecharts.charts import Linedef visualize_index_trend(data_file):"""绘制收录量趋势图"""# 读取数据df = pd.read_csv(data_file)# 按日期分组汇总df['date'] = pd.to_datetime(df['timestamp']).dt.datetrend_data = df.groupby('date')['index_count'].sum().reset_index()# 使用matplotlib绘制plt.figure(figsize=(12, 6))plt.plot(trend_data['date'], trend_data['index_count'], marker='o')plt.title('百度收录量趋势图')plt.xlabel('日期')plt.ylabel('收录量')plt.grid(True)plt.xticks(rotation=45)plt.tight_layout()plt.savefig('index_trend.png')plt.show()# 使用pyecharts绘制交互式图表line = (Line().add_xaxis(trend_data['date'].astype(str).tolist()).add_yaxis("收录量", trend_data['index_count'].tolist(), is_smooth=True).set_global_opts(title_opts=opts.TitleOpts(title="百度收录量趋势图"),toolbox_opts=opts.ToolboxOpts(is_show=True),xaxis_opts=opts.AxisOpts(name="日期"),yaxis_opts=opts.AxisOpts(name="收录量"),tooltip_opts=opts.TooltipOpts(trigger="axis")))line.render("index_trend.html")
五、注意事项与合规提醒
5.1 百度规则遵守
请勿频繁请求(建议每次请求间隔不少于 3 秒)
不要使用爬虫抓取非公开数据
尊重百度的 robots.txt 协议
5.2 法律风险提示
本工具仅用于个人或企业对自有网站的收录量监控
禁止用于抓取他人网站数据或进行商业用途
因不当使用导致的任何法律后果由使用者自行承担
5.3 技术局限性
百度收录量显示存在延迟,可能与实际收录情况有差异
部分新发布内容可能未及时显示在收录量中
百度可能随时变更搜索结果页面结构,导致抓取规则失效
通过以上方法,你可以轻松实现百度收录量的自动化监控,为内容创作和 SEO 优化提供数据支持。记得定期检查代码是否正常工作,并根据百度页面结构的变化及时调整解析规则。如果你在使用过程中遇到问题,欢迎在评论区交流讨论!
