-
Notifications
You must be signed in to change notification settings - Fork 3
/
WeiboCommentScrapy.py
155 lines (130 loc) · 6.56 KB
/
WeiboCommentScrapy.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
import requests
import os, sys
requests.packages.urllib3.disable_warnings()
from lxml import etree
from datetime import datetime, timedelta
from threading import Thread
import csv
from math import ceil
import os
import re
from time import sleep
from random import randint
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
'Cookie': '''SCF=AtXLglXmCgR8AbTdUcSocE6mcnl_Mk232fDtiB0lfc4_t4daI7YiDvfSi29hqDxN2krttq2Vd36tu7BF_d493vQ.; login_sid_t=3a25024492e5a6807c7531609f5e8af2; cross_origin_proto=SSL; _s_tentry=cn.bing.com; Apache=3573941561831.7373.1618126514882; SINAGLOBAL=3573941561831.7373.1618126514882; ULV=1618126514898:1:1:1:3573941561831.7373.1618126514882:; TC-V-WEIBO-G0=35846f552801987f8c1e8f7cec0e2230; XSRF-TOKEN=ZBlPsUguNTD9xnw1UZibOqsk; SSOLoginState=1618378415; SUB=_2A25Ncg7_DeRhGeBO6FMU9CbEyjuIHXVunJK3rDV8PUJbkNANLRDakW1NSgy_LWAhRW3ewHUQ0DtF2AtdQONlb1PI; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9W5ajGj7bbOjdh3e96f3nQCF5NHD95QcehepSKBR1h2NWs4DqcjiqcvadsxLM._T; wvr=6; UOR=cn.bing.com,weibo.com,www.baidu.com; wb_view_log_6031548817=1366*7681.75; webim_unReadCount=%7B%22time%22%3A1618480799471%2C%22dm_pub_total%22%3A0%2C%22chat_group_client%22%3A0%2C%22chat_group_notice%22%3A0%2C%22allcountNum%22%3A50%2C%22msgbox%22%3A0%7D; wb_timefeed_6031548817=1'''
}
class WeiboCommentScrapy(Thread):
def __init__(self,wid):
global headers
Thread.__init__(self)
self.headers = headers
self.result_headers = [
'评论者主页',
'评论者昵称',
'评论者性别',
'评论者所在地',
'评论者微博数',
'评论者关注数',
'评论者粉丝数',
'评论内容',
'评论获赞数',
'评论发布时间',
]
if not os.path.exists('comment'):
os.mkdir('comment')
self.wid = wid
self.start()
def parse_time(self,publish_time):
publish_time = publish_time.split('来自')[0]
if '刚刚' in publish_time:
publish_time = datetime.now().strftime('%Y-%m-%d %H:%M')
elif '分钟' in publish_time:
minute = publish_time[:publish_time.find('分钟')]
minute = timedelta(minutes=int(minute))
publish_time = (datetime.now() -
minute).strftime('%Y-%m-%d %H:%M')
elif '今天' in publish_time:
today = datetime.now().strftime('%Y-%m-%d')
time = publish_time[3:]
publish_time = today + ' ' + time
elif '月' in publish_time:
year = datetime.now().strftime('%Y')
month = publish_time[0:2]
day = publish_time[3:5]
time = publish_time[7:12]
publish_time = year + '-' + month + '-' + day + ' ' + time
else:
publish_time = publish_time[:16]
return publish_time
def getPublisherInfo(self,url):
res = requests.get(url=url,headers=self.headers,verify=False)
html = etree.HTML(res.text.encode('utf-8'))
head = html.xpath("//div[@class='ut']/span[1]")[0]
head = head.xpath('string(.)')[:-3].strip()
keyIndex = head.index("/")
nickName = head[0:keyIndex-2]
sex = head[keyIndex-1:keyIndex]
location = head[keyIndex+1:]
footer = html.xpath("//div[@class='tip2']")[0]
weiboNum = footer.xpath("./span[1]/text()")[0]
weiboNum = weiboNum[3:-1]
followingNum = footer.xpath("./a[1]/text()")[0]
followingNum = followingNum[3:-1]
followsNum = footer.xpath("./a[2]/text()")[0]
followsNum = followsNum[3:-1]
print(nickName,sex,location,weiboNum,followingNum,followsNum)
return nickName,sex,location,weiboNum,followingNum,followsNum
def get_one_comment_struct(self,comment):
# xpath 中下标从 1 开始
userURL = "https://weibo.cn/{}".format(comment.xpath(".//a[1]/@href")[0])
content = comment.xpath(".//span[@class='ctt']/text()")
# '回复' 或者只 @ 人
if '回复' in content or len(content)==0:
test = comment.xpath(".//span[@class='ctt']")
content = test[0].xpath('string(.)').strip()
# 以表情包开头造成的 content == 0,文字没有被子标签包裹
if len(content)==0:
content = comment.xpath('string(.)').strip()
content = content[content.index(':')+1:]
else:
content = content[0]
praisedNum = comment.xpath(".//span[@class='cc'][1]/a/text()")[0]
praisedNum = praisedNum[2:praisedNum.rindex(']')]
publish_time = comment.xpath(".//span[@class='ct']/text()")[0]
publish_time = self.parse_time(publish_time)
nickName,sex,location,weiboNum,followingNum,followsNum = self.getPublisherInfo(url=userURL)
return [userURL,nickName,sex,location,weiboNum,followingNum,followsNum,content,praisedNum,publish_time]
def write_to_csv(self,result,isHeader=False):
with open('comment/' + self.wid + '.csv', 'a', encoding='utf-8-sig', newline='') as f:
writer = csv.writer(f)
if isHeader == True:
writer.writerows([self.result_headers])
writer.writerows(result)
print('已成功将{}条评论写入{}中'.format(len(result),'comment/' + self.wid + '.csv'))
def run(self):
res = requests.get('https://weibo.cn/comment/{}'.format(self.wid),headers=self.headers,verify=False)
commentNum = re.findall("评论\[.*?\]",res.text)[0]
commentNum = int(commentNum[3:len(commentNum)-1])
print(commentNum)
pageNum = ceil(commentNum/10)
print(pageNum)
for page in range(pageNum):
result = []
res = requests.get('https://weibo.cn/comment/{}?page={}'.format(self.wid,page+1), headers=self.headers,verify=False)
html = etree.HTML(res.text.encode('utf-8'))
comments = html.xpath("/html/body/div[starts-with(@id,'C')]")
print('第{}/{}页'.format(page+1,pageNum))
for i in range(len(comments)):
result.append(self.get_one_comment_struct(comments[i]))
if page==0:
self.write_to_csv(result,isHeader=True)
else:
self.write_to_csv(result,isHeader=False)
sleep(randint(1,5))
if __name__ =="__main__":
if len(sys.argv) != 2:
print("Usage: %s weibo_id" % sys.argv[0])
sys.exit(-1)
# WeiboCommentScrapy(wid='IaYZIu0Ko')
WeiboCommentScrapy(wid=sys.argv[1])