按要求完成对博思平台社区(http://cqcvc.iflysse.com/Pages/Ask/Index.aspx)话题信息进行爬取并保存。
(1)使用cookie模拟登录博思教学平台。
(2)爬取博思平台社区话题【标题、悬赏、作者、回复数、发布时间】5个字段。
(3)创建表名 ifly_comm_info,字段名【id,title,score,author,ansnum,pubtime】。
(4)将爬取到的数据保存到数据库。
这是我们收到的要求!!接下来我们创建一个账号分析一下网页
这里我们可以看到我们需要的信息都在这里
接下来我们看看它是异步请求数据还是就在网页源码里的数据,大部分网站都是采用的异步加载数据,所以这里我们就直接看它的请求
然后我们发现一串有用的信息,这正是我们想要的数据,接下来就是分析请求了
分析如下,我们可以看到使用的post请求,数据类型form data
知道这些就简单了.
#-*- cdoeing = utf-8 -*-
#@Time : 2020-12-17
#@Author : LBOcean
import requests
import pymysql
url = 'http://cqcvc.iflysse.com/Handler/AskHandler.ashx'
heard = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
'Cookie': '这里写网页的cooike'
}
payload = {
'sEcho': 1,
'iColumns': 6,
'sColumns': ',,,,,',
'iDisplayStart': 0,
'iDisplayLength': 20,
'mDataProp_0': 0,
'bSortable_0': False,
'mDataProp_1': 'Title',
'bSortable_1': False,
'mDataProp_2': 2,
'bSortable_2': False,
'mDataProp_3': 3,
'bSortable_3': False,
'mDataProp_4': 4,
'bSortable_4': False,
'mDataProp_5': 'SubmitTimeStr',
'bSortable_5': False,
'iSortCol_0': 1,
'sSortDir_0': 'desc',
'iSortingCols': 1,
'Type': 0,
'action': 2,
'IsOver': 1,
'LabelList': []
} #from data 数据
#连接数据库
db = pymysql.connect(host="localhost",
user="root",
passwd="110120",
db="hous")
print("数据库连接成功")
cursor = db.cursor()
for i in range(0,20*20+1,20):#每页又20个数据,获取20页
data_str_start = 'sEcho=1&iColumns=6&sColumns=%2C%2C%2C%2C%2C&iDisplayStart='
data_str_end = '&iDisplayLength=20&mDataProp_0=0&bSortable_0=false&mDataProp_1=Title&bSortable_1=false&mDataProp_2=2&bSortable_2=false&mDataProp_3=3&bSortable_3=false&mDataProp_4=4&bSortable_4=false&mDataProp_5=SubmitTimeStr&bSortable_5=false&iSortCol_0=1&sSortDir_0=desc&iSortingCols=1&Type=0&action=2&IsOver=1&LabelList=%5B%5D'
data_end = data_str_start + str(i) + data_str_end#这里我们采用了拼接的方式来获取数据
home = requests.post(url=url, headers=heard, data=data_end).json() # json解析数据
dataforce = home['aaData']#我们想要的数据在aaData后面,所以这里过滤掉了前面的数据
# print(dataforce.encoding)
for e in dataforce:
title = e["Title"]
score = e["Score"]
author = e["SubmitterName"]
ansnum = e["AnswerNum"]
pubtime = e["SubmitTime"]
value = (title,score,author,ansnum,pubtime)
sql = 'INSERT INTO ifly_comm_info(title,score,author,ansnum,pubtime) values(%s,%s,%s,%s,%s)'
if cursor.execute(sql,value):
print("插入成功")
db.commit()
print(title)
print(score)
print(author)
print(ansnum)
print(pubtime)
数据库信息
CREATE TABLEifly_comm_info
(
id
int NOT NULL AUTO_INCREMENT,
title
varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
score
float(30,0) NOT NULL,
author
varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
ansnum
float(30,0) NOT NULL,
pubtime
varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB AUTO_INCREMENT=1302 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
这里我就简单的截取一段数据库信息