-
Notifications
You must be signed in to change notification settings - Fork 0
/
save_html.py
361 lines (315 loc) · 10.2 KB
/
save_html.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#!/usr/bin/env python
#coding=utf-8
import socket
import urllib
import urllib2
import ssl
from bs4 import BeautifulSoup
import base64
import re
import sys
from gzip import GzipFile
from StringIO import StringIO
from selenium import webdriver
import time
import os
import platform
# set the position of chrome-driver
if platform.uname()[0] == "Linux":
os.environ['PATH'] = "/usr/lib/chromium-browser/:" + os.environ['PATH']
elif platform.uname()[0] == "Windows":
os.environ['PATH'] = "./Chrome/Application/;" + os.environ['PATH']
# import cookielib
# #声明一个CookieJar对象实例来保存cookie
# cookie = cookielib.CookieJar()
# #利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器
# handler = urllib2.HTTPCookieProcessor(cookie)
# #通过handler来构建opener
# opener = urllib2.build_opener(handler)
# #此处的open方法同urllib2的urlopen方法,也可以传入request
data_url_format = "data:image/%(image_type)s;base64,%(image_base64)s"
style_format = "<style type=\"text/css\">\n%(css_text)s</style>"
support_image_data_type = ["png", "jpeg", "gif"]
protocol = ""
host = ""
referer = ""
website = ""
path = ""
global_headers = {}
_protocol = ""
_host = ""
_referer = ""
_website = ""
_path = ""
# def set_extra_headers(_headers):
# global headers
def get_host(url):
global protocol
global host
global referer
global website
global path
protocol, s1 = urllib.splittype(url)
host, path = urllib.splithost(s1)
website = protocol + "://" + host
referer = website + "/"
# print protocol
# print host
# print referer
# exit(0)
return host
def get_temp_host(url):
global _protocol
global _host
global _referer
global _website
global _path
_protocol, s1 = urllib.splittype(url)
_host, _path = urllib.splithost(s1)
_website = _protocol + "://" + _host
_referer = _website + "/"
# print protocol
# print host
# print referer
# exit(0)
return _host
def page_title(html):
bsObj = BeautifulSoup(html, "lxml")
title = bsObj.select("title")
return str(title[0].contents[0].encode('utf-8'))
# 外部样式表
# 当样式需要被应用到很多页面的时候,外部样式表将是理想的选择。使用外部样式表,你就可以通过更改一个文件来改变整个站点的外观。
# <head>
# <link rel="stylesheet" type="text/css" href="mystyle.css">
# </head>
# 内部样式表
# 当单个文件需要特别样式时,就可以使用内部样式表。你可以在 head 部分通过 <style> 标签定义内部样式表。
# <head>
# <style type="text/css">
# body {background-color: red}
# p {margin-left: 20px}
# </style>
# </head>
def external_css_to_internal_css(css_url):
return get_data(css_url)
# pass
def gzip_unpack(data):
buf = StringIO(data)
f = GzipFile(fileobj=buf)
return f.read()
def get_data_from_file(path):
html = ""
try:
fd = open(path, "r")
html = fd.read()
pass
except Exception as e:
raise e
finally:
if None != fd:
fd.close()
pass
return html
def get_data(url, headers = {}, content_type = {}):
times = 0
while times < 10:
try:
return _get_data(url, headers, content_type)
pass
except Exception as e:
# raise e
pass
times += 1
raise e
def _get_data(url, headers = {}, content_type = {}):
print url
get_temp_host(url)
global _host
global _referer
global global_headers
if len(headers) > 0:
global_headers = headers
_headers = {
"Host": _host,
"Referer": _referer,
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/68.0.3440.75 Chrome/68.0.3440.75 Safari/537.36",
# "Cookie": "comment_author_email_e7382aacd190d171a15486ff88d472d4=178344859%40qq.com; comment_author_e7382aacd190d171a15486ff88d472d4=%E5%B9%95%E5%88%83; acw_tc=AQAAAM+xtjBw7QoAyjKIdSS0WtHc1ekT; PHPSESSID=hktconai6jh2934b4htm4vlmo1; Hm_lvt_cc53db168808048541c6735ce30421f5=1534786653,1534818378,1534826430,1534905415; 3cb185a485c81b23211eb80b75a406fd=1534925182; acw_sc__=5b7d2e3e4dea9aa5630697a57b5f3722d705a095; Hm_lpvt_cc53db168808048541c6735ce30421f5=1534930892"
}
_headers.update(headers)
_headers.update(global_headers)
print _headers
# **************************************************
# urllib2.HTTPError: HTTP Error 400: Bad Request
# urllib2.quote(url)
# **************************************************
req = urllib2.Request(urllib2.quote(url, ":/=&?"), headers = _headers)
# res = urllib2.urlopen(req)
# solve ssl error
res = urllib2.urlopen(req, timeout=30, context=ssl._create_unverified_context())
print res.info()
# print res.headers["Content-Type"]\
try:
content_type["type"] = res.headers["Content-Type"].split("/")[1]
pass
except Exception as e:
pass
print content_type
data = res.read()
return data
# return gzip_unpack(data)
def get_rendered_data(url, headers = {}):
# 创建chrome参数对象
chrome_options = webdriver.ChromeOptions()
# 把chrome设置成无界面模式,不论windows还是linux都可以,自动适配对应参数
chrome_options.set_headless()
# chrome_options.add_argument('--no-sandbox')#解决DevToolsActivePort文件不存在的报错
chrome_options.add_argument("–start-maximized") # –start-maximized 启动就最大化
# chrome_options.add_argument('window-size=1920x3000') #指定浏览器分辨率
chrome_options.add_argument('--disable-gpu') #谷歌文档提到需要加上这个属性来规避bug
chrome_options.add_argument('--hide-scrollbars') #隐藏滚动条, 应对一些特殊页面
chrome_options.add_argument('--blink-settings=imagesEnabled=false') #不加载图片, 提升速度
chrome_options.add_argument('--headless') #浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
chrome_options.add_argument("--ignore-certificate-errors");
chrome_options.add_argument('lang=zh_CN.UTF-8')
if False:
chrome_options.binary_location = "./Chrome/Application/chrome.exe" #手动指定使用的浏览器位置
# 创建chrome无界面对象
driver = webdriver.Chrome(options=chrome_options)
# driver = webdriver.Chrome()
html = ""
try:
driver.get(url)
time.sleep(5)
html = driver.find_element_by_css_selector("html").get_attribute("outerHTML").encode("utf-8")
pass
except Exception as e:
raise e
pass
finally:
driver.close()
driver.quit()
pass
return html
# data:image/png;base64, iVBORw0KGgoAAAANSUhEUg
def image2base64(image_url, content_type = {}):
data = get_data(image_url, content_type = content_type)
# print content_type
return base64.b64encode(data)
def image_url_to_data_url(image_url):
content_type = {}
image_type = "png"
image_base64 = image2base64(image_url, content_type)
print content_type
if content_type.get("type") != None:
image_type = content_type["type"]
return data_url_format % ({"image_type": image_type, "image_base64": image_base64})
def get_lazy_load_url(image_node):
for key in image_node.attrs:
# print image_node[key];
image_url = image_node[key]
# if re.match("data-\\w", key) != None and re.match(".+\\.(gif|jpeg|png)$", image_url):
if re.match("data-\\w", key) != None and re.match("(https?://.+|.+\\.(gif|jpeg|png)$)", image_url):
return image_url
return None
def find_image_url(html):
bsObj = BeautifulSoup(html, "lxml")
img_list = bsObj.select("img")
# image_url_list = []
for img in img_list:
# data_original = img["data-original"]
print img.attrs
img_src = ""
lazyload_url = get_lazy_load_url(img)
if lazyload_url == None:
lazyload_url = img.get("data-original") or img.get("data-src")
if img.get("src") != None and img.get("src") != "":
img_src = img['src']
if lazyload_url != None:
img_src = lazyload_url
print img_src
if "" == img_src:
continue
if img_src.startswith("data:"):
continue
if img_src.startswith("//"):
img_src = protocol + ":" + img_src
if img_src.startswith("/"):
img_src = website + img_src
if not img_src.startswith("http"):
global path
# deal with following situation
# static/drops/full/e0e2b28abc7ca327236f462324ef315e652220c4.jpg
# http://www.anquan.us/static/drops/papers-17213.html
# http://www.anquan.us/static/drops/full/e0e2b28abc7ca327236f462324ef315e652220c4.jpg
dirs = path[:path.rindex('/') + 1].split("/")
img_dirs = img_src.split("/")
index = 0
while dirs.count(img_dirs[index]) > 0:
index += 1
img_src = "/".join(img_dirs[index:])
img_src = website + path[:path.rindex('/') + 1] + img_src
# image_url_list.append(img_src)
data_url = image_url_to_data_url(img_src)
img["src"] = data_url
# exit(0)
return str(bsObj)
def find_css_link(html):
bsObj = BeautifulSoup(html, "lxml")
css_list = bsObj.select("link")
css_url_list = []
for css in css_list:
# print css['rel']
# print str(css)
if css["rel"].count("stylesheet") > 0:
# print css['href']
css_url_list.append(css)
return css_url_list
def style2dict(style):
d = {}
for line in style.split(";"):
key_value = line.split(":")
if len(key_value) == 2:
d[key_value[0]] = key_value[1]
return d
def dict2style(d):
style = ""
for key in d:
style += (key + ":" + d[key] + ";")
return style
if __name__ == '__main__':
if len(sys.argv) < 2:
exit(0)
article_url = sys.argv[1]
print get_host(article_url)
html = get_data(article_url)
title = page_title(html)
# html = find_image_url(html)
# image_url_list = find_image_url(html)
# for image_url in image_url_list:
# data_url = image_url_to_data_url(image_url)
# # print data_url
# html = html.replace(image_url, data_url)
# css_link_list = find_css_link(html)
# for css_link in css_link_list:
# print "+" * 80
# css_url = css_link['href']
# _css_url = css_url
# if css_url.startswith("//"):
# css_url = protocol + ":" + css_url
# if css_url.startswith("/"):
# css_url = website + css_url
# print css_url
# css_text = external_css_to_internal_css(css_url)
# # print css_text
# # html = html.replace(str(css_link), style_format % ({"css_text": css_text}))
# print str(css_link)
# pattern = re.compile(r'<link.*href=[\'\"]' + _css_url.replace("?", "\\?") + r'[\'\"].*>')
# print pattern.pattern
# print pattern.findall(html)
# style_text = style_format % ({"css_text": css_text})
# style_text = style_text.replace("\\", "\\\\")
# html = re.sub(pattern, style_text, html)
# print "=" * 80
fhandle = open(title + ".html", "w")
fhandle.write(html)
fhandle.close()