1.安装Beautiful Soup库
在Python环境中输入以下命令来安装库:
!pip install beautifulsoup4
2.导入库及其他必要的库
在Python程序中导入以下库及其他必要的库:
from urllib.request import urlopen
from bs4 import BeautifulSoup
3.获取维基百科页面数据
通过以下代码获取维基百科页面数据:
url = "https://zh.wikipedia.org/wiki/Python"
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
4.解析页面数据
使用Beautiful Soup解析数据并提取所需的信息:
# 提取标题
title = soup.title
print(title)
# 提取页面中所有链接
for link in soup.find_all('a'):
print(link.get('href'))
打印结果如下:
Python - 维基百科,自由的百科全书
/wiki/Wikipedia:%E9%A6%96%E9%A1%B5
/wiki/Wikipedia:%E7%BB%B4%E5%9F%BA%E7%99%BE%E7%A7%91
/wiki/%E7%BB%B4%E5%9F%BA%E7%99%BE%E7%A7%91:%E5%85%B3%E4%BA%8E%E7%BB%B4%E5%9F%BA%E7%99%BE%E7%A7%91
/wiki/%E7%BB%B4%E5%9F%BA%E7%99%BE%E7%A7%91:%E7%99%BE%E7%A7%91%E5%88%86%E7%B1%BB
...
以上就是使用Beautiful Soup库提取维基百科页面信息的解决方法。