-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathanalyse.py
214 lines (181 loc) · 7.13 KB
/
analyse.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# encoding=utf-8
"""sina_search
hits: http://finance.sina.com.cn/stock/jsy/20141125/043020909481.shtml
"""
import json
import sys
import logging
import unittest
import requests
import os
import re
import time
from bs4 import BeautifulSoup
DEBUG = False
if DEBUG:
level = logging.DEBUG
else:
level = logging.ERROR
logging.basicConfig(level=level, format="%(levelname)s %(asctime)s %(lineno)d:: %(message)s")
class Analysis(object):
def __init__(self, path, url=None):
self.path = path
self.url = url
self.comment_id = None
self.comment_count = None
self.soup = None
self.result = {}
self.text = None
def parse(self):
if os.path.exists(self.path) is False:
url_time = re.search(r'\d{8}', self.url)
if url_time != None:
self.parse_url(url_time.group(0))
self.parse_comment_url()
if self.comment_id != None:
self.parse_show_and_total()
self.parse_comment_contents()
else:
self.result["show"] = ''
self.result["total"] = ''
self.result["comment_contents"] = ''
else:
self.result = {"media_name": "", "title": "", "show": "", "content": "", "time": "", "keywords": "", "total": "", "comment_contents": ""}
return self.result
else:
with open(self.path, "r") as f:
self.text = f.read()
self.soup = BeautifulSoup(self.text, "html5lib")
self.result["show"] = ''
self.result["total"] = ''
self.result["comment_contents"] = ''
self.parse_title()
self.parse_time()
self.parse_media_name()
self.parse_keywords()
self.parse_content()
logging.debug("result is %s", json.dumps(self.result, indent=4))
def parse_url(self, url_time):
r = requests.get(self.url)
if int(url_time) > 20121031:
try:
self.soup = BeautifulSoup(r.content.decode('gbk'), "html5lib")
except:
self.soup = BeautifulSoup(r.content, "html5lib")
else:
try:
self.soup = BeautifulSoup(r.content.decode('gbk'), "html.parser")
except:
self.soup = BeautifulSoup(r.content, "html.parser")
def parse_comment_url(self):
news_id = re.search(r'\d{12}', self.url)
if news_id == None:
news_id = re.search(r'\d{11}', self.url)
if news_id == None:
self.comment_id = None
else:
self.comment_id = news_id.group(0)[4:11]
else:
self.comment_id = news_id.group(0)[4:12]
def parse_show_and_total(self):
jscontent = requests.get("http://comment5.news.sina.com.cn/page/info?format=js&channel=cj&newsid=31-1-" + self.comment_id +"&group=&compress=1&ie=gbk&oe=gbk&page=1&page_size=100&jsvar=requestId").content
jscontent = jscontent.replace('var requestId=', '')
js_dict = json.loads(jscontent)
js_data = js_dict.get('result')
js_count = js_data.get('count')
try:
self.result["show"] = js_count.get('show')
self.result["total"] = js_count.get('total')
except:
self.result["show"] = ''
self.result["total"] = ''
self.comment_count = self.result["show"]
def parse_comment_contents(self):
count = 1
self.result["comment_contents"] = {}
for page in range(1, ((self.comment_count-1)/100)+2):
jscontent = requests.get("http://comment5.news.sina.com.cn/page/info?format=js&channel=cj&newsid=31-1-" + self.comment_id +"&group=&compress=1&ie=gbk&oe=gbk&page=" + str(page) +"&page_size=100&jsvar=requestId").content
jscontent = jscontent.replace('var requestId=', '')
js_dict = json.loads(jscontent)
js_data = js_dict.get('result')
cmntlist = js_data.get('cmntlist')
try:
for each in cmntlist:
comment_content = each.get('content')
self.result["comment_contents"]["content_" + str(count)] = comment_content
count += 1
except:
time.sleep(0.01)
def parse_title(self):
h1 = self.soup.find("h1", {"id": "artibodyTitle"})
if h1 != None:
self.result["title"] = h1.get_text().strip()
else:
self.result["title"] = ''
def parse_time(self):
span = self.soup.find("span", {"id": "pub_date"})
if span != None:
self.result["time"] = span.get_text().strip()
else:
self.result["time"] = ''
def parse_media_name(self):
span = self.soup.find("span", {"id": "media_name"})
if span != None:
if span.a == None:
self.result["media_name"] = span.get_text().strip()
else:
self.result["media_name"] = span.a.get_text().strip()
else:
self.result["media_name"] = ''
def parse_keywords(self):
keyword = ''
p = self.soup.find("p", {"class": "art_keywords"})
if p != None:
p = p.find_all('a')
for a in p:
keyword += a.string
self.result["keywords"] = keyword
def parse_content(self):
div = self.soup.find("div", {"id": "artibody"})
content = ''
if div != None:
div = div.find_all('p')
for p in div:
if p.string == None:
p = self.soup.find('span')
for span in p:
try:
content += span.get_text()
except:
pass
else:
content += p.get_text()
self.result["content"] = content
class TestAnalysis(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
self.path = "5950.txt"
def test_parse(self):
"""http://finance.sina.com.cn/stock/jsy/20141125/043020909481.shtml
"""
self.analysis = Analysis(self.path, "http://finance.sina.com.cn/stock/jsy/20141125/043020909481.shtml")
self.analysis.parse()
self.assertNotEqual(self.analysis.result, {})
self.assertIsNotNone(self.analysis.result["title"])
self.assertIsNotNone(self.analysis.result["time"])
self.assertIsNotNone(self.analysis.result["media_name"])
self.assertIsNotNone(self.analysis.result["keywords"])
self.assertIsNotNone(self.analysis.result["show"])
self.assertIsNotNone(self.analysis.result["total"])
self.assertIsNotNone(self.analysis.result["content"])
self.assertIsNotNone(self.analysis.result["comment_contents"])
if __name__ == "__main__":
if DEBUG:
unittest.main()
in_data = sys.stdin.read()
logging.debug("in data is: %s", in_data)
in_json = json.loads(in_data)
url = in_json.get("url")
analysis = Analysis(in_json["path"], url)
analysis.parse()
print json.dumps(analysis.result)