使用Python从Wikipedia的信息框中获取文本
在本文中,我们将使用BeatifulSoup和Python中的请求从Wikipedia的信息框中抓取文本。我们可以在10分钟内完成。很简单。
我们需要安装bs4和请求。执行以下命令进行安装。
pip install bs4 pip install requests
请按照以下步骤编写代码,以从信息框中获取所需的文本。
导入bs4和request模块。
使用request.get()方法将HTTP请求发送到要从中获取数据的页面。
使用bs4.BeautifulSoup类解析响应文本,并将其存储在变量中。
转到Wikipedia页面并检查所需的元素。
使用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"
结论
您可以通过检查并在Wikipedia页面中找到所需的任何数据。如果您对本教程有任何疑问,请在评论部分中提及。