标签:try encoding 完成 inf odi soup 程序设计 except lis
总体而言:
分析源代码,查看需要爬取的内容在什么位置
从图片中可以看出,排名信息是在<tbody>
标签
具体的信息是在<tr>
标签下的<td>
标签内的string
def getHMLText(url):
'''
获取url信息,输出url的内容,来抓取网页的信息
'''
try:
r = request.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return "抓取失败!"
def UnivList(ulist, html):
'''
提取html中的数据,放入到ulist列表,完成数据提取
'''
soup = BeautifulSoup(html, "html.parser")
for tr in soup.find('tbody').children:
if isinstance(tr, bs4.element.Tag): # 判断tr的子节点是否为非属性字符串
tds = tr('td')
# print(tds)
# print('#' * 30)
# print(tds[0], tds[0].string)
# print('#' * 30)
# print(tds[1], tds[1].string)
# print('#' * 30)
# print(tds[2], tds[2].string)
# print('#' * 30)
# print(tds[3], tds[3].string)
ulist.append([tds[0].string, tds[1].string, tds[3].string, tds[2].string])
def printUnivList(ulist, num):
'''
将ulist列表信息打印,num表示打印前多少排名的学校
'''
print("{:^3}\t{:^10}\t{:^20}\t{:^30}".format("排名", "学校名称", "总分", '地址'))
for i in range(num):
u = ulist[i]
print("{:^3}\t{:^10}\t{:^20}\t{:^30}".format(u[0], u[1], u[2], u[3]))
def main():
'''
实现整个代码
'''
ulist = []
url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html'
html = getHTMLText(url)
UnivList(ulist, html)
printUnivList(ulist, 100)
main()
import requests
import bs4
from bs4 import BeautifulSoup
def getHMLText(url):
'''
获取url信息,输出url的内容,来抓取网页的信息
'''
try:
r = request.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return "抓取失败!"
def UnivList(ulist, html):
'''
提取html中的数据,放入到ulist列表,完成数据提取
'''
soup = BeautifulSoup(html, "html.parser")
for tr in soup.find('tbody').children:
if isinstance(tr, bs4.element.Tag): # 判断tr的子节点是否为非属性字符串
tds = tr('td')
# print(tds)
# print('#' * 30)
# print(tds[0], tds[0].string)
# print('#' * 30)
# print(tds[1], tds[1].string)
# print('#' * 30)
# print(tds[2], tds[2].string)
# print('#' * 30)
# print(tds[3], tds[3].string)
ulist.append([tds[0].string, tds[1].string, tds[3].string, tds[2].string])
def printUnivList(ulist, num):
'''
将ulist列表信息打印,num表示打印前多少排名的学校
'''
print("{:^3}\t{:^10}\t{:^20}\t{:^30}".format("排名", "学校名称", "总分", '地址'))
for i in range(num):
u = ulist[i]
print("{:^3}\t{:^10}\t{:^20}\t{:^30}".format(u[0], u[1], u[2], u[3]))
def main():
'''
实现整个代码
'''
uinfo = []
url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html'
html = getHTMLText(url)
fillUnivList(uinfo, html)
printUnivList(uinfo, 100)
main()
标签:try encoding 完成 inf odi soup 程序设计 except lis
原文地址:https://www.cnblogs.com/moniter/p/12334232.html