-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlecture.py
171 lines (152 loc) · 7.01 KB
/
lecture.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
# Created on 2017-03-28 22:14:07
# Project: LecturePush
from pyspider.libs.base_handler import *
import re
from datetime import datetime
from pyspider.libs.base_handler import *
import pymysql
conn = pymysql.connect(host='ip', user='root', passwd='pass', db='db', charset="utf8")
cursor = conn.cursor()
class Handler(BaseHandler):
crawl_config = {
'headers': {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, sdch",
"Accept-Language": "zh-CN,zh;q=0.8",
"Cache-Control": "max-age=0",
"Connection": "keep-alive",
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36', }
}
def __init__(self):
self.conn = conn
self.cursor = cursor
sql = '''
CREATE TABLE IF NOT EXISTS Lecture(
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(100),
lecturetime datetime,
place VARCHAR(100),
speaker VARCHAR(100),
speakerbrif TEXT,
detail TEXT
)ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;'''
self.cursor.execute(sql)
self.conn.commit()
@every(minutes=3 * 60)
def on_start(self):
self.crawl(
'http://www.swjtu.edu.cn/jsp/activity.jsp?page=1&siteId=12163&catalogPath=-12163-12259-&selectDay=&searchType=month&address=&keyword=&hdType=',
callback=self.swjtu_page, validate_cert=False, auto_recrawl=True,last_modified=False)
self.crawl('http://dean.swjtu.edu.cn/servlet/LectureAction?Action=LectureMore&SelectType=Month',
callback=self.dean_page, validate_cert=False, auto_recrawl=True,last_modified=False)
def swjtu_page(self, response):
for each in response.doc('[cmsid="34403899"] a').items():
self.crawl(each.attr.href, callback=self.swjtu_detail_page)
currentpage = response.doc('div.page_blue span.current').text()
if not currentpage == "":
if int(currentpage) <= 7:
for each in response.doc('.page_blue a').items():
if (each.text() == '>>'):
self.crawl(each.attr.href, callback=self.swjtu_page)
def dean_page(self, response):
html = response.doc('script')
lecture_pages = re.findall('var allPage = "(.*?)"', html.text(), re.S)[0]
for each in response.doc('[style="float:left;width:735px;"] a').items():
self.crawl(each.attr.href, callback=self.dean_detail_page,last_modified=False)
if lecture_pages > 1:
for item in range(2, int(lecture_pages) + 1):
lecture_page_link = 'http://dean.swjtu.edu.cn/servlet/LectureAction?Action=LectureMore&SelectType=Month&page={}'.format(
item)
self.crawl(lecture_page_link, callback=self.dean_page,last_modified=False)
def handleTime(self, text):
text = text.split('---')[0]
timenum = re.sub("\D", "", text)
time = datetime.strptime(timenum, '%Y%m%d%H%M')
return time
def deadTime(self, now):
month = now.month - 2; # 只爬取前两个月的
if month < 1:
month = month + 12
return datetime.strptime(str(now.year) + str(month), '%Y%m')
def close_crawl(self):
pass
@config(priority=2)
def swjtu_detail_page(self, response):
title = response.doc(
'[style="width:545px; height:45px; float:left; line-height:40px; font-size:14px; color:#505050; font-weight:bold;"]').text()
speakerbrief = response.doc(
'[style="width:530px; height:45px; float:left; line-height:14px; font-size:12px; color:#505050;"]').text()
speaker = response.doc(
'[style="width:545px; height:21px; background:url(/themes/12163/default/images/xswnhd3.jpg) no-repeat; float:left;line-height:20px;"]').text()
place = response.doc(
'[style="width:545px; height:21px; background:url(/themes/12163/default/images/xswnhd4.jpg) no-repeat; float:left;line-height:20px;"]').text()
date = response.doc(
'[style="width:726px; height:40px; line-height:40px; text-align:left; margin:10px 0px 0px 16px; background:url(/themes/12163/default/images/xswnhd2.jpg);"]').text()
time = response.doc(
'[style="width:50px; height:80px; margin:10px auto; text-align:center; font-size:14px; font-weight:bold; line-height:23px; color:#6c6c6c;"]').text()
time = self.handleTime(date + " " + time)
detail = response.doc('[style="width:700px; height:auto; margin:0 auto;"]').text()
deadtime = self.deadTime(datetime.now())
if time >= deadtime:
return {
"title": title,
"speaker": speaker,
"speakerbrif": speakerbrief,
"time": time.strftime('%Y-%m-%d %H:%M'),
"detail": detail,
"place": place,
}
@config(priority=2)
def dean_detail_page(self, response):
title = ""
line = 0
speakerbrief = ""
time = datetime.now()
place = ""
speaker = ""
for each in response.doc('table#table1 tr td').items():
if line == 0:
title = each.text()
if line == 3:
time = self.handleTime(each.text())
if line == 4:
place = each.text()
if line == 5:
speaker = each.text()
if line == 7:
speakerbrief = each.text()
if line == 9:
detail = '嘉宾介绍:'.decode('utf8')+speakerbrief + '\n' + '演讲内容:'.decode('utf8')+each.text()
line = line + 1
deadtime = self.deadTime(datetime.now())
if time >= deadtime:
return {
"title": title,
"speaker": speaker,
"speakerbrif": speakerbrief,
"time": time.strftime('%Y-%m-%d %H:%M'),
"detail": detail,
"place": place,
}
def on_result(self, result):
if not result:
return
super(Handler, self).on_result(result)
title = result['title']
time = result['time']
place = result['place']
speaker = result['speaker']
speakerbrif = result['speakerbrif']
detail = result['detail']
self.cursor.execute('SELECT 1 FROM Lecture WHERE title=%s LIMIT 1', title) #插入前判断是否存在
if len(cursor.fetchall()) == 0:
self.cursor.execute(
'INSERT INTO Lecture(title, lecturetime, place, speaker, speakerbrif, detail) VALUES (%s, %s, %s, %s, %s, %s)',
(title, time, place, speaker, speakerbrif, detail))
self.conn.commit()
#self.conn.commit()
print('insert success!')
else:
print('data has already exists.')