如何限制打印的字符串数量?

时间:2016-12-14 08:26:46

标签: list python-3.x wikipedia

以下是我的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

1 个答案:

答案 0 :(得分:0)

您只需执行for link in links[:3]:即可显示列表中的前三个元素。