首页 / 爬虫 / 网络爬虫爬取中国大学排名,并存入数据库
网络爬虫爬取中国大学排名,并存入数据库
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了网络爬虫爬取中国大学排名,并存入数据库,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1696字,纯文字阅读大概需要3分钟。
内容图文
#CrawUnivRanjingA.py
import requests
from bs4 import BeautifulSoup
import bs4
import pymysql
db=pymysql.connect(host="localhost",user="root",password="admin",db="test",port=3306)
print('数据库连接成功')
cursor=db.cursor()
# cursor.execute()
# sql = """CREATE TABLE Daxue (
# 排名 int(3) NOT NULL,
# 学校名称 CHAR(10),
# 总分 float (2),
# 省市 varchar(10))"""
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):
a=0
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[3].string,tds[2].string])
paiming=tds[0].text.strip()
xuexiaomingcheng=tds[1].text.strip()
zongfeng=tds[3].text.strip()
shengshi=tds[2].text.strip()
if a<20:
insert_into = ("INSERT INTO Daxue(排名,学校名称,总分,省市)""VALUES(%s,%s,%s,%s)")
data_into=(paiming,xuexiaomingcheng,zongfeng,shengshi)
cursor.execute(insert_into,data_into)
db.commit()
a+=1
def PrintUnivlist(ulist,NUM):
tplt="{0:<10}\t{1:{4}<10}\t{2:<10}\t{3:<10}"
print(tplt.format("排名","学校名称","总分","省市",chr(12288)))
for i in range(NUM):
u=ulist[i]
print(tplt.format(u[0],u[1],u[2],u[3],chr(12288)))
def main():
uinfo=[]
url="http://www.zuihaodaxue.com/zuihaodaxuepaiming2019.html"
html=getHTMLtEXT(url)
fillUnivList(uinfo,html)
PrintUnivlist(uinfo,20)
main()
存入数据库后:
内容总结
以上是互联网集市为您收集整理的网络爬虫爬取中国大学排名,并存入数据库全部内容,希望文章能够帮你解决网络爬虫爬取中国大学排名,并存入数据库所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。