这段时间突然对网络爬虫比较感兴趣,于是入手了一下。今天看到一个大学排名的网站,想将网页上的排名信息爬取下来。代码如下:
import
requests
import
bs4
from
bs4
import
BeautifulSoup
import
re
def
getHTMLText(url):
try
:
r = requests.get(url,
timrout
=
30
)
r.raise_for_status()
r.encoding = r.apparent_encoding
return
r.text
except
:
return
""
def
fillUnivList(ulist, html):
soup = BeautifulSoup(html,
"html.parser"
)
tbody
= soup.find(
'tbody'
)
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):
print
(
"{:^10}
\t
{:^10}
\t
{:^10}"
.format(
"排名"
,
"大学名称"
,
"总分"
))
for
i
in
range
(num):
u = ulist[i]
print
(
"{:^10}
\t
{:^10}
\t
{:^10}"
.format(u[
0
],u[
1
],u[
2
]))
def
main():
#num = int(raw_input("请输入您要查询的大学数:"))
unifo = []
url =
"http://www.gaokaopai.com/paihang-otype-2.html?f=1&ly=bd&city=&cate=&batch_type="
html = getHTMLText(url)
print
(html)
fillUnivList(unifo, html)
printUnivList(unifo,
10
)
main()
运行一下,提示错误:
for tr in soup.find('tbody').children: AttributeError: 'NoneType' object has no attribute 'children'
调试了一天,也上网搜了很多,但怎么也没有解决,下午打完球回来一看,突然发现自己好傻,原来是getHTMLText()函数中的
r = requests.get(url,
timrout
=
30
)
这一句中的timeout打错字了,不过为什么呢?苦恼的我开始继续百度,终于功夫不负有心人,找到了答案:
首先,解析一下这个错误提示,大体的意思就是soup.find()这个函数返回的对象没有children这个属性;
这就很好办了,问题已经确定,就在soup.find()中,于是上网搜了一下find()函数,发现其返回的对象又children这个属性,应该没错,又想到是不是查找的‘tbody’没有子类,查看源代码后发现有,顿时懵了,还有其他的原因吗,想了一个小时,突然想到会不会连最起码的网页内容都没获取到,于是先尝试输出网页源代码,果然,没有,于是去看getHTMLText函数,发现了错误所在