以下是我的python3程序,用于显示维基百科类别的12个子类别。它打印12个子类别。现在,我想只显示前3个子类别。怎么样?但是在将来开发我的程序时,我将把所有12个子类别写在一个文件中。
from bs4 import BeautifulSoup
import requests
url = 'https://en.wikipedia.org/wiki/Category:proprietary software'
content = requests.get(url).content
soup = BeautifulSoup(content,'lxml')
noOFsubcategories = soup.find('p')
print('------------------------------------------------------------------')
print(noOFsubcategories.text+'------------------------------------------------------------------')
tag = soup.find('div', {'class' : 'mw-category'})
links = tag.findAll('a')
counter = 1
for link in links:
print ( str(counter) + " " + link.text)
counter = counter + 1
答案 0 :(得分:0)
您只需执行for link in links[:3]:
即可显示列表中的前三个元素。