标签里,利用创建的soup对象搜索节点
(四)完整代码
把获得的数据传入数据库进行保存
# -*-coding=utf-8-*-
import re
import urllib
import urllib2
import cookielib
from bs4 import BeautifulSoup
import pymysql.cursors
# 连接数据库
connection = pymysql.connect(
host='localhost',
user='root',
password='',
db='chenji',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor,
)
# 模拟登陆
loginUrl = 'http://online.gxut.edu.cn/cmzx/StudentsMediaCentre.php/Index/login/chengji/1.html'
# cookie
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
values = {
'userName': '201500402079',
'password': 'xxxxxx',
'submit': '登入'
}
postdata = urllib.urlencode(values)
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36',
'Referer': 'http://online.gxut.edu.cn/cmzx/StudentsMediaCentre.php/Index/login/chengji/1.html',
'Cookie': 'PHPSESSID=0pa9gpq62pi6hvcf8018b77hg0'
}
request = urllib2.Request(loginUrl, postdata, header)
print (postdata)
response = urllib2.urlopen(request)
print response.getcode()
html_cont = response.read()
print html_cont
soup = BeautifulSoup(html_cont, 'html.parser', from_encoding='utf-8')
arr = soup.find(id="biaoge").find_all("td")
cj = []
for x in arr:
ch = x.get_text()
print ch
strings = ch
cj.append(strings)
if len(cj) == 14:
try:
with connection.cursor() as cursor:
sql = "INSERT INTO cj(xh, student, semester, classname, leixing, xuefen, pingshi, mid, qimo, total, xz, point, classcode, shic)VALUES (%s, %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql, (cj[0], cj[1], cj[2], cj[3], cj[4], cj[5], cj[6], cj[7], cj[8], cj[9], cj[10], cj[11], cj[12], cj[13]))
connection.commit()
finally:
cj = []
print "insert succeed!"
pass
(五)个人感悟
1.因为是刚开始学习爬虫知识,各种不懂,到处碰壁,可能一个小小的、很简单的点儿,在我的手里都要琢磨很久——对知识不了解,反复反复,一次又一次的error,一个一个地去百度,甚至一天下来,什么也解决,内心里都要快气炸了,有一种对自己“恨铁不成钢”的感觉,但是还是一次次选择去解决。
2.从学习这个装了很多软件,很多版本,或许Python的2.x和Python的3.x的不同吗,让我在安装第三方插件的时候,就匹配的这个问题上吃了一些苦头。让我想起那天,毕业的学长在实验室的一句话“先有广度,才有深度”。趁着自己年轻,多去接触不同的东西,无论是生活方面的,还是专业知识的,对自己都有很大的帮助!
2017.7.22 六
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved.
京ICP备09083238号