-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrawler.py
67 lines (56 loc) · 2.01 KB
/
crawler.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
# -*- coding: utf-8 -*-
import random
import time
import logging
import MySQLdb
from downloader import WeiboDownloader
class WeiboCrawler:
MYSQL_HOST = 'local'
MYSQL_USERNAME = 'root'
MYSQL_PASSWORD = ''
MYSQL_DATABASE = 'weibo'
MYSQL_PORT = 3306
MYSQL_CHARSET = 'utf8mb4'
def __init__(self,
isConnectMySQL=False,
htmlOutputDir=''):
self._keywords = None
self._pages = None
self._htmlOutputDir = htmlOutputDir
self._isConnectMySQL = isConnectMySQL
self._conn = None
self.hasResult = True
if self._isConnectMySQL:
self._conn = MySQLdb.connect(
host='127.0.0.1' if self.MYSQL_HOST == 'local' else self.MYSQL_HOST,
user=self.MYSQL_USERNAME,
passwd=self.MYSQL_PASSWORD,
db=self.MYSQL_DATABASE,
port=self.MYSQL_PORT,
charset=self.MYSQL_CHARSET,
use_unicode=False)
print u'连入数据库'
# def search(self, keywords, pages):
# if type(keywords) is str:
# self._search_keyword(keywords)
# elif type(keywords) is list:
# for keyword in keywords:
# self._search_keyword(keyword)
# else:
# print 'Keywords TypeError'
def search(self, keywords, pages=range(1,51)):
if type(keywords) is str:
for page in pages:
downloader = WeiboDownloader(keywords, page, self._conn, self._htmlOutputDir).load().retrieve()
self.hasResult = downloader.hasResult
if self.hasResult:
sec = random.uniform(5, 15)
print '随机睡眠' + str(sec) + '秒\n'
time.sleep(sec)
else:
break
elif type(keywords) is list:
for keyword in keywords:
self.search(keyword, pages)
else:
print 'Keywords TypeError, please enter str or list.'