一个简单的网页排名爬取,但是返回的内容是空的
爬虫的目的是爬取http://www.zuihaodaxue.com/zuihaodaxuepaiming2019.html这个网页上的大学排名列表。但是返回的内容是空的。import requestsfrom 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(.string,tds.string,tds.string])
def printUnivList(ulist,num):
print("{:^10}\t{:^6}\t{:^10}".format("排名","学校名称","总分"))
for i in range(num):
u=ulist
print("{:^10}\t{:^6}\t{:^10}".format("u","u","u"))
defmain():
uinfo=[]
url=" http://www.zuihaodaxue.com/zuihaodaxuepaiming2019.html"
html = getHTMLText(url)
fillUnivList(uinfo,html)
printUnivList(uinfo,20)
main()
本帖最后由 Twilight6 于 2020-4-30 17:43 编辑
你没有设置函数的retuen吧 最后 def main():
uinfo = []
url = " http://www.zuihaodaxue.com/zuihaodaxuepaiming2019.html"
html = getHTMLText(url)
fillUnivList(uinfo, html)
return printUnivList(uinfo, 20)
要retuen才有返回值
还有这
def printUnivList(ulist, num):
print("{:^10}\t{:^6}\t{:^10}".format("排名", "学校名称", "总分"))
for i in range(num):
u = ulist
print("{:^10}\t{:^6}\t{:^10}".format(u, u, u))
这里你把u, u, u,加上了引号应该去掉把 我这里显示是可以得到结果的
另外,你总分爬取写错了
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(.string, tds.string, tds.string])
def printUnivList(ulist, num):
print("{:^10}\t{:^6}\t{:^10}".format("排名", "学校名称", "总分"))
for i in range(num):
u = ulist
print("{:^10}\t{:^10}\t{:^10}".format(u, u, u))
def main():
uinfo = []
url = " http://www.zuihaodaxue.com/zuihaodaxuepaiming2019.html"
html = getHTMLText(url)
fillUnivList(uinfo, html)
return printUnivList(uinfo, 20)
main()
都帮你改了下,就是总分那边不居中
页:
[1]