为了获取高校的创办时间所写的代码,写的不好,其中有些学校获取不到,请见谅。高校名单可以上教育部官网查询,这里不加赘述。`
import requests #爬虫库
from bs4 import BeautifulSoup #html文本解析库
import bs4
rf=open('C:/Users/20382/Desktop/高校/高校名单.csv','r')
wf=open('C:/Users/20382/Desktop/高校/高校创办时间.csv',"a")
wf.seek(0)
wf.truncate()
def gettime(name):
html=requests.get("https://baike.baidu.com/item/"+name,timeout=30,headers={'user-agent':'Mozilla/5.0'})
html.encoding='utf-8'
demo=html.text
results=BeautifulSoup(demo,"html.parser")#文本解析
context=(results.find('div',"basic-info cmn-clearfix").text.replace('\n',''))
#print(context)
start=context.find("创办时间")
time=(context[start+4:start+8])
return time
i=0
schoolslist=rf.readlines()
for school in schoolslist:
schoolname=(school.replace('\n',''))
i=i+1
try:
time=gettime(schoolname)
print(str(i)+","+schoolname+","+time)
wf.write(str(i)+","+schoolname+","+time+"\n")
except:
print(str(i)+","+schoolname+",无时间")
wf.write(str(i)+","+schoolname+",无时间\n")
rf.close()
wf.close()