爬取wikipedia词条

本文介绍了一种使用Python中的BeautifulSoup库从Wikipedia主页抓取链接的方法。通过正则表达式筛选出所有以/wiki开头的链接,并排除了图片链接。
#导入Beautifulsoup包
from bs4 import BeautifulSoup as bs
from urllib.request import urlopen
import re

# 请求URL并把结果用utf-8编码
resp=urlopen("https://en.wikipedia.org/wiki/Main_page").read().decode("utf-8")
# 使用BeautifulSoup去解析
soup=bs(resp,"html.parser")
# 获取所有以/wiki开头的a 标签的href属性
listUrls=soup.findAll("a",href=re.compile("^/wiki/"))
# 打印出url
for url in listUrls:
    # print(url) #打印出来是整条a标签
    if not re.search("\.(jpg|JPG)$",url["href"]): #上面取的有包含.jpg的图片,故要在href属性中排除
        #将url的名字+"https://en.wikipedia.org"+url中的href属性合并打印出来
        print(url.get_text(),"<---->","https://en.wikipedia.org"+url["href"])
<think>我们正在处理一个关于Python爬取Wikipedia的请求。用户要求教程,因此我们需要提供清晰的步骤。参考引用中提到了使用API、BeautifulSoup和Requests,以及处理反爬虫机制等。我们将按照这些要点构建教程。注意:根据引用,Wikipedia提供了API,通常推荐使用API而不是直接爬取HTML,因为API更稳定且符合规则。步骤:1.介绍两种方法:使用WikipediaAPI和直接爬取HTML(使用BeautifulSoup)2.分别给出两种方法的示例代码3.提醒遵守robots.txt和Wikipedia的使用条款由于引用中提到了使用BeautifulSoup和Requests,以及API,我们将分别展示。注意:引用[1]提到“通过API获取数据”,引用[2]提到“抓取页面的标题、正文和链接”,引用[3]给出了一个使用find函数的例子(BeautifulSoup)。因此,我们可以这样组织:方法一:使用WikipediaAPI(推荐)方法二:使用Requests和BeautifulSoup解析HTML然后,我们给出存储数据和处理反爬虫的建议。同时,根据系统指令,数学公式用$...$,独立公式用$$...$$(但本问题可能较少涉及数学公式,但如果有变量等,我们会注意格式)。最后,生成相关问题。</think>### Python Wikipedia 网页爬虫教程 以下是使用 Python 爬取 Wikipedia 数据的完整步骤,结合 API 和 HTML 解析两种方法: #### 一、准备工作 1. **安装必要库**: ```bash pip install requests beautifulsoup4 pandas ``` 2. **了解 Wikipedia 规则**: - 遵守 `robots.txt`([https://en.wikipedia.org/robots.txt](https://en.wikipedia.org/robots.txt)) - 设置合理请求间隔(建议 ≥ 1 秒/请求) - 使用 API 优先于直接爬取 HTML[^1] #### 二、方法 1:使用 Wikipedia API(推荐) ```python import requests def fetch_wiki_api(title): endpoint = "https://en.wikipedia.org/w/api.php" params = { "action": "query", "format": "json", "titles": title, "prop": "extracts", "explaintext": True # 获取纯文本 } try: response = requests.get(endpoint, params=params, timeout=10) data = response.json() page = next(iter(data["query"]["pages"].values())) return page["extract"] # 返回正文内容 except Exception as e: print(f"API 请求失败: {e}") return None # 示例:获取 "Python (programming language)" 词条 content = fetch_wiki_api("Python_(programming_language)") print(content[:500]) # 打印前500字符 ``` #### 三、方法 2:使用 BeautifulSoup 解析 HTML ```python from bs4 import BeautifulSoup import re def scrape_wiki_html(url): headers = {'User-Agent': 'Mozilla/5.0'} # 模拟浏览器 try: response = requests.get(url, headers=headers) soup = BeautifulSoup(response.content, 'html.parser') # 提取标题 title = soup.find("h1", {"id": "firstHeading"}).text # 提取正文(根据引用[3]方法改进) content_div = soup.find("div", {"id": "bodyContent"}) paragraphs = content_div.find_all("p") text = "\n".join(p.text for p in paragraphs if p.text.strip()) # 提取所有内部链接(引用[3]的正则表达式) links = content_div.find_all("a", href=re.compile(r"^(/wiki/)((?!:).)*$")) return {"title": title, "content": text, "links": links} except Exception as e: print(f"HTML 解析失败: {e}") return None # 示例:爬取 Web scraping 词条 data = scrape_wiki_html("https://en.wikipedia.org/wiki/Web_scraping") print(f"标题: {data['title']}") print(f"正文长度: {len(data['content'])} 字符") ``` #### 四、数据存储与处理 ```python import pandas as pd # 存储为 CSV def save_to_csv(data, filename): df = pd.DataFrame([data]) df.to_csv(filename, index=False, encoding='utf-8-sig') # 存储到 SQLite import sqlite3 def save_to_sqlite(data, db_name="wikipedia.db"): conn = sqlite3.connect(db_name) cursor = conn.cursor() cursor.execute('''CREATE TABLE IF NOT EXISTS pages (title TEXT, content TEXT)''') cursor.execute("INSERT INTO pages VALUES (?, ?)", (data['title'], data['content'])) conn.commit() conn.close() ``` #### 五、反爬虫处理技巧 1. **请求头设置**: ```python headers = { 'User-Agent': 'ResearchBot/1.0 (contact@example.com)', 'Accept-Language': 'en-US,en;q=0.5' } ``` 2. **请求限速**: ```python import time time.sleep(1.5) # 每次请求间隔 ``` 3. **代理轮换**(需自备代理池): ```python proxies = {"http": "http://10.10.1.10:3128"} requests.get(url, proxies=proxies) ``` #### 六、最佳实践建议 1. 优先使用官方 API(`action=query`) 2. 避免高频请求(>50 次/分钟可能被封 IP) 3. 处理重定向:检查 API 返回中的 `redirects` 字段 4. 遵循 Wikipedia 的机器人政策:[Bot Policy](https://meta.wikimedia.org/wiki/Bot_policy) > 提示:完整项目代码可参考 Wikipedia 爬虫实战教程[^2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值