Skip to content

Commit

Permalink
fix dataabc#265: overwrite when delete flag id & notify
Browse files Browse the repository at this point in the history
  • Loading branch information
haozewu committed Mar 27, 2022
1 parent 0fd4f77 commit 8a88dbe
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 9 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -594,3 +594,9 @@ txt文件名格式可以参考[程序设置](#3程序设置)中的设置user_id_
3. 将提供cookie的微博id放置在`config.json`文件中`"user_id_list"`设置项数组中的第一个。例如提供cookie的微博id为`123456`,则`"user_id_list"`设置为`"user_id_list":["123456", "<其余id...>"]`

注:本方法也将会抓取提供cookie账号的微博内容。

在间歇运行程序时,cookie无效会导致程序不能按照预设目标执行,因此可以打开cookie通知功能。本项目使用开源项目[pushdeer](https://github.com/easychen/pushdeer)进行通知,在使用前用户需要申请push_key,具体可查看官网了解。打开方法为:

1.`const.py`文件中,将`'NOTIFY': False`中的`False`设为`True`
2.`'PUSH_KEY': ''``''`替换为`'<你的push_key>'`

4 changes: 4 additions & 0 deletions const.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,7 @@
'EXIT_AFTER_CHECK': False, # 这里不要动,append模式中已完成增量微博抓取,仅等待cookie检查的标志位
'HIDDEN_WEIBO': '微博内容', # 你可能发现平台会自动给你的微博自动加个空格,但这里你不用加空格
}
const.NOTIFY = {
'NOTIFY': False, # 是否通知
'PUSH_KEY': '', # 这里使用push_deer做通知,填入pushdeer的pushkey
}
6 changes: 3 additions & 3 deletions util/csvutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


def insert_or_update_user(logger, headers, result_data, file_path):
"""插入或更新用户csv。不存在则插入,最新抓取微博id不填,存在则先不动,返回已抓取最新微博id"""
"""插入或更新用户csv。不存在则插入,最新抓取微博id不填,存在则先不动,返回已抓取最新微博id和日期"""
first_write = True if not os.path.isfile(file_path) else False
if os.path.isfile(file_path):
# 文件已存在,直接查看有没有,有就直接return了
Expand All @@ -24,14 +24,14 @@ def insert_or_update_user(logger, headers, result_data, file_path):
return ''


def update_last_weibo_id(userid, new_last_weibo_id, file_path):
def update_last_weibo_id(userid, new_last_weibo_msg, file_path):
"""更新用户csv中的最新微博id"""
lines = []
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
if line.split(',')[0] == str(userid):
line = line.replace(line.split(
',')[len(line.split(',')) - 1], str(new_last_weibo_id) + '\n')
',')[len(line.split(',')) - 1], new_last_weibo_msg + '\n')
lines.append(line)
f.close()
with open(file_path, 'w', encoding='utf-8') as f:
Expand Down
9 changes: 9 additions & 0 deletions util/dateutil.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@

import datetime


def convert_to_days_ago(date_str, how_many_days):
"""将日期字符串转换为多少天前的日期字符串"""
date_str = datetime.datetime.strptime(date_str, '%Y-%m-%d')
date_str = date_str + datetime.timedelta(days=-how_many_days)
return date_str.strftime('%Y-%m-%d')
11 changes: 11 additions & 0 deletions util/notify.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import requests
import const


def push_deer(append_str):
params = {
'pushkey': const.NOTIFY['PUSH_KEY'],
'text': append_str,
}
# 这里为了避免证书验证,使用http而非https
requests.get(url="http://api2.pushdeer.com/message/push", params=params)
21 changes: 15 additions & 6 deletions weibo.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
from tqdm import tqdm

from util import csvutil
from util.dateutil import convert_to_days_ago
from util.notify import push_deer

warnings.filterwarnings("ignore")

Expand Down Expand Up @@ -204,15 +206,16 @@ def user_to_csv(self):
result_headers = [
'用户id', '昵称', '性别', '生日', '所在地', '学习经历', '公司', '注册时间', '阳光信用',
'微博数', '粉丝数', '关注数', '简介', '主页', '头像', '高清头像', '微博等级', '会员等级',
'是否认证', '认证类型', '认证信息', '上次记录微博id'
'是否认证', '认证类型', '认证信息', '上次记录微博信息'
]
result_data = [[
v.encode('utf-8') if 'unicode' in str(type(v)) else v
for v in self.user.values()
]]
# 已经插入信息的用户无需重复插入,返回的id是\n或者具体的id
self.last_weibo_id = csvutil.insert_or_update_user(logger, result_headers, result_data, file_path)

# 已经插入信息的用户无需重复插入,返回的id是空字符串或微博id 发布日期%Y-%m-%d
last_weibo_msg = csvutil.insert_or_update_user(logger, result_headers, result_data, file_path)
self.last_weibo_id = last_weibo_msg.split(' ')[0] if last_weibo_msg else ''
self.last_weibo_date = last_weibo_msg.split(' ')[1] if last_weibo_msg else self.user_config['since_date']
def user_to_mongodb(self):
"""将爬取的用户信息写入MongoDB数据库"""
user_list = [self.user]
Expand Down Expand Up @@ -276,7 +279,7 @@ def get_user_info(self):
"""获取用户信息"""
params = {'containerid': '100505' + str(self.user_config['user_id'])}
# TODO 这里在读取下一个用户的时候很容易被ban,需要优化休眠时长
sleep(random.randint(6, 10))
sleep(random.randint(10, 20))
js, status_code = self.get_json(params)
if status_code != 200:
logger.info(u"被ban了,需要等待一段时间")
Expand Down Expand Up @@ -941,7 +944,7 @@ def get_one_page(self, page):
if self.first_crawler and not self.is_pinned_weibo(w):
# 置顶微博的具体时间不好判定,将非置顶微博当成最新微博,写入上次抓取id的csv
self.latest_weibo_id = str(wb['id'])
csvutil.update_last_weibo_id(wb['user_id'], wb['id'], self.user_csv_file_path)
csvutil.update_last_weibo_id(wb['user_id'], str(wb['id']) + ' ' + wb['created_at'], self.user_csv_file_path)
self.first_crawler = False
if str(wb['id']) == self.last_weibo_id:
if const.CHECK_COOKIE['CHECK'] and (not const.CHECK_COOKIE['CHECKED']):
Expand All @@ -953,6 +956,10 @@ def get_one_page(self, page):
else:
logger.info('增量获取微博完毕,将最新微博id从 {} 变更为 {}'.format(self.last_weibo_id, self.latest_weibo_id))
return True
# 上一次标记的微博被删了,就把上一条微博时间记录推前两天,多抓点评论或者微博内容修改
# TODO 更加合理的流程是,即使读取到上次更新微博id,也抓取增量评论,由此获得更多的评论
since_date = datetime.strptime(
convert_to_days_ago(self.last_weibo_date, 2), '%Y-%m-%d')
if created_at < since_date:
if self.is_pinned_weibo(w):
continue
Expand All @@ -977,6 +984,8 @@ def get_one_page(self, page):
logger.info(u'正在过滤转发微博')
if const.CHECK_COOKIE['CHECK'] and not const.CHECK_COOKIE['CHECKED']:
logger.warning('经检查,cookie无效,系统退出')
if const.NOTIFY['NOTIFY']:
push_deer('经检查,cookie无效,系统退出')
sys.exit()
else:
return True
Expand Down

0 comments on commit 8a88dbe

Please sign in to comment.