一個簡單的python分頁小模塊
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
#url連接,countdatas表數(shù)據(jù)總行數(shù)饶辙,currentpage第幾頁(0是第一頁)蛾默,everpage每頁多少行,beforlaterln前后長度
def pagestr(url,countdatas,currentpage,everpage,beforlaterln):
page=""
intpart=countdatas/everpage
remainderpart=countdatas%everpage #余數(shù)
countpage=int(intpart) #取整數(shù)
currentpage=(0 if (currentpage<0) else currentpage)
if remainderpart==0:#余數(shù)判斷
currentpage=(countpage-1 if (currentpage>countpage-1) else currentpage)
countpage;#總頁數(shù)
pp=currentpage+1
strbe=""
pagebefore=pp-beforlaterln-1
i = pp
while i>pagebefore :
if i>0 and i<pp:
strbe="<a class='num' href='"+url+"&p="+str(i-1)+"'>"+str(i)+"</a>"+strbe
i -= 1
if pp<=1:
strbe=""
else:
strbe="<a class='num' href='"+url+"&p=0'>首頁</a>"+"<a class='num' href='"+url+"&p="+str(pp-2)+"'>上一頁</a>"+strbe
strmid="<span class='current'>"+str(pp)+"</span>"
strlater=""
pagelater=pp+beforlaterln
i=pp
while i < pagelater:
if i<countpage:
strlater+="<a class='num' href='"+url+"&p="+str(i)+"'>"+str(i+1)+"</a>"
i += 1
if pp>=countpage:
d=0
else:
strlater+="<a class='num' href='"+url+"&p="+str(pp)+"'>下一頁</a>"+"<a class='num' href='"+url+"&p="+str(countpage-1)+"'>尾頁</a>"
page=strbe+strmid+strlater
else:
countpage+=1 #總頁數(shù)
currentpage=(countpage-1 if (currentpage>countpage-1) else currentpage)
pp=currentpage+1
strbe=""
pagebefore=pp-beforlaterln-1
i = pp
while i>pagebefore :
if i>0 and i<pp:
strbe="<a class='num' href='"+url+"&p="+str(i-1)+"'>"+str(i)+"</a>"+strbe
i -= 1
if pp<=1:
strbe=""
else:
strbe="<a class='num' href='"+url+"&p=0'>首頁</a>"+"<a class='num' href='"+url+"&p="+str(pp-2)+"'>上一頁</a>"+strbe
strmid="<span class='current'>"+str(pp)+"</span>"
strlater=""
pagelater=pp+beforlaterln
i=pp
while i < pagelater:
if i<countpage:
strlater+="<a class='num' href='"+url+"&p="+str(i)+"'>"+str(i+1)+"</a>"
i += 1
if pp>=countpage:
d=0
else:
strlater+="<a class='num' href='"+url+"&p="+str(pp)+"'>下一頁</a>"+"<a class='num' href='"+url+"&p="+str(countpage-1)+"'>尾頁</a>"
page=strbe+strmid+strlater
return "共"+str(countpage)+"頁"+page
pages = pagestr('http://www.abc.com?',195,11,10,8)
print (pages)
運行后得到以下字符串
共20頁<a class='num' >首頁</a>
<a class='num' >上一頁</a>
<a class='num' >4</a>
<a class='num' >5</a>
<a class='num' >6</a>
<a class='num' >7</a>
<a class='num' >8</a>
<a class='num' >9</a>
<a class='num' >10</a>
<a class='num' >11</a>
<span class='current'>12</span>
<a class='num' >13</a>
<a class='num' >14</a>
<a class='num' >15</a>
<a class='num' >16</a>
<a class='num' >17</a>
<a class='num' >18</a>
<a class='num' >19</a>
<a class='num' >20</a>
<a class='num' >下一頁</a>
<a class='num' >尾頁</a>
希望對大家有幫助静尼,謝謝工窍!