本篇分享讲爬取中国高校排名前100名并将其写入MySQL,这样做的好处是:1.将数据存入数据库,能永久利用;2.能利用数据库技术做一些其他操作。爬取的网页是:http://gaokao.xdf.cn/201702/10612921.html
1. 环境:
windows10
python3
mysql 5.7
2.开始
安装各个模块:
pip install bs4
pip install pymysql
导入:
import bs4
import pymysql
import urllib.request
from bs4 import BeautifulSoup
先利用urllib和BeautifulSoup爬取前100名的表格,返回list形式,再利用MySQLdb将list写入数据中,其代码如下:
def get_html(url):
html = urllib.request.urlopen(url)
content = html.read()
html.close()
soup = BeautifulSoup(content, "lxml")
table = soup.find('tbody')
count = 0
lst = []
for tr in table.children:
if isinstance(tr, bs4.element.Tag):
td = tr('td')