使用Python从维基百科信息框中提取文本
在这篇文章中,我们将使用Python中的BeautifulSoup和requests库来抓取维基百科信息框中的文本。我们可以在10分钟内完成,非常简单。
我们需要安装bs4和requests。执行以下命令进行安装。
pip install bs4 pip install requests
按照以下步骤编写代码,以提取我们想要的信息框文本。
- 导入bs4和requests模块。
- 使用requests.get()方法向要从中提取数据的页面发送HTTP请求。
- 使用bs4.BeautifulSoup类解析响应文本,并将其存储在一个变量中。
- 访问维基百科页面并检查所需的元素。
- 使用bs4提供的合适方法查找元素。
让我们看看下面的示例代码。
示例
# importing the module
import requests
import bs4
# URL
URL = "https://en.wikipedia.org/wiki/India"
# sending the request
response = requests.get(URL)
# parsing the response
soup = bs4.BeautifulSoup(response.text, 'html')
# Now, we have paresed HTML with us. I want to get the _motto_ from the wikipedia page.
# Elements structure
# table - class="infobox"
# 3rd tr to get motto
# getting infobox
infobox = soup.find('table', {'class': 'infobox'})
# getting 3rd row element tr
third_tr = infobox.find_all('tr')[2]
# from third_tr we have to find first 'a' element and 'div' element to get required data
first_a = third_tr.div.find('a')
div = third_tr.div.div
# motto
motto = f"{first_a.text} {div.text[:len(div.text) - 3]}"
# printing the motto
print(motto)如果运行上述程序,您将得到以下结果。
输出
Satyameva Jayate "Truth Alone Triumphs"
结论
您可以通过检查维基百科页面并查找元素来获取任何想要的数据。如果您对本教程有任何疑问,请在评论区提出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP