我是一个刚入门python爬虫的小白,准备把学习爬虫过程中遇到的问题记录在这里,与大家共勉。
今天这个问题主要是粗心+基础不扎实原因造成的,跟着老师打代码,结果出现了IndexError: tuple index out of range的问题,主要原因是把chr(12288)
写成了chr = (12288)
,在str.format()
函数中没有变量的写法,因此它的参数与前面的槽对应不是,出现错误。# 具体程序内容
输入:大学排名URL链接
输出:大学排名信息的屏幕输出(排名,大学名称,总分)
技术路线:requests-bs4
定向爬虫:仅对输入URL进行爬取,不扩展爬取
1.从网络上获取大学排名的网页内容
getHTMLText()
2.提取网页信息到合适的数据结构
fillUnivList()
3.利用数据结构展示并输出结果
printUnivList()
import requests
from bs4 import BeautifulSoup
import bs4
def getHTMLText(url):
try:
r = requests.get(url, timeout = 30)
r.raise_for_status
r.encoding = r.apparent_encoding
return r.text
except:
return '错误'
def fillUnivList(ulist, html):
soup = BeautifulSoup(html, 'html.parser')
for tr in soup.find('tbody').children:
if isinstance(tr, bs4.element.Tag):
tds = tr('td')
ulist.append([tds[0].string, tds[1].string, tds[2].string])
def printUnivList(ulist, num):
tblt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
print(tblt.format('排名', '学校名称', '总分', chr = (12288)))
for i in range(num):
u = ulist[i]
print(tblt.format(u[0], u[1], u[2], chr = (12288)))
print('Suc' + str(num))
def main():
uinfo = []
url = "http://www.zuihaodaxue.com/zuihaodaxuepaiming2016.html"
html = getHTMLText(url)
fillUnivList(uinfo, html)
printUnivList(uinfo, 20) # 20 univs
main()
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
in
----> 1 main()
in main()
4 html = getHTMLText(url)
5 fillUnivList(uinfo, html)
----> 6 printUnivList(uinfo, 20) # 20 univs
in printUnivList(ulist, num)
1 def printUnivList(ulist, num):
2 tblt = "{0:^10}\t{1:{3}^15}\t{2:^10}"
----> 3 print(tblt.format('排名', '学校名称', '总分', chr = (12288)))
4 for i in range(num):
5 u = ulist[i]
IndexError: tuple index out of range