Python维基百科数据爬虫遇保护限制报错,求解决方案
解决维基百科爬虫被反爬拦截的问题
嘿Larry!作为新手刚接触爬虫就碰到维基的反爬,太正常啦~维基百科确实有专门的机制拦截非浏览器的机器人请求,咱们一步步来解决你的问题:
最省心的方案:用官方维基Python库
直接用官方维护的wikipedia-api,完全不用操心反爬,还能直接获取页面内容和链接,简直是新手福音!
步骤1:安装库
打开命令行运行:
pip install wikipedia-api
步骤2:示例代码(直接获取页面+提取链接)
import wikipediaapi # 这里一定要填自己的用户代理信息,维基要求标识你的爬虫 wiki_client = wikipediaapi.Wikipedia( language='zh', # 改成你需要的语言,比如'en'是英文 user_agent='ProjectX/1.0 (your-email@example.com)' # 替换成你的项目名和邮箱 ) # 获取目标页面 target_page = wiki_client.page("Python (编程语言)") if target_page.exists(): print(f"页面标题: {target_page.title}") # 提取页面里的所有维基链接 print("\n页面中的相关链接:") for link_title, link_page in target_page.links.items(): # 过滤掉文件、特殊页面这类非内容链接 if not link_title.startswith("File:") and not link_title.startswith("Special:"): print(f"- {link_title}: https://zh.wikipedia.org/wiki/{link_title.replace(' ', '_')}") else: print("页面不存在哦!")
如果你坚持自己写爬虫(requests+BeautifulSoup)
那得做好反爬规避,核心是模拟浏览器请求+控制请求频率:
示例代码
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/118.0.0.0 Safari/537.36' } def crawl_wiki_page(url): try: # 发送请求 response = requests.get(url, headers=headers) response.raise_for_status() # 如果请求失败(比如403)直接抛出错误 # 解析页面 soup = BeautifulSoup(response.text, 'html.parser') # 提取所有维基内容链接(过滤掉文件、特殊页面) wiki_links = [] for a_tag in soup.find_all('a', href=True): href = a_tag['href'] if (href.startswith('/wiki/') and not href.startswith('/wiki/File:') and not href.startswith('/wiki/Special:')): full_link = f"https://zh.wikipedia.org{href}" wiki_links.append(full_link) return wiki_links except requests.exceptions.RequestException as e: print(f"请求出错啦: {e}") return [] # 测试爬取 target_url = "https://zh.wikipedia.org/wiki/Python_(编程语言)" links = crawl_wiki_page(target_url) print("提取到的链接:") for link in links[:10]: # 只打印前10个示例 print(f"- {link}") # 爬取下一页前一定要休息几秒,别给维基服务器压力 time.sleep(3)
重要提醒!
一定要遵守维基百科的robots.txt规则(比如不要爬取/wiki/Special:开头的特殊页面),不然可能会被永久封禁IP哦~
内容的提问来源于stack exchange,提问作者Larry




