python利用selenium抓取网页返回值

工作中遇到利用html进行pdf加密浏览的状况,只能有限次打开,并且还不能打印,不能保存,感觉有些不开心,所以,我想攻克它,首先想到的是对js进行破解,发现有点难,后来想通过在源代码中提取pdf发现加密了,不好搞,又想通过服务器端入手,也发现有点难以实现。后来在无意中看到chrome中的network的log,于是我灵机一动,人生苦短,不如python。说干就干,终有下文。我的思路是:先通过浏览器模拟浏览,然后抓取浏览日志缓存,提取缓存然后还原文件,把还原后的图片合成pdf。

功能

  • 将通过html形式加密的pdf进行还原

准备

  • python
  • selenium
  • webdriver.exe与自己的chrome匹配

上代码

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
#!/usr/bin/env python 
# -*- coding:utf-8 -*-
# @Time : 2021-07-20 16:17
# @Author :
# @Email :
# @File : test2.py
# @Software: PyCharm
"""info

"""
# -*- coding=utf-8 -*-
import json
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from urllib.parse import urlparse


def netloc_info(url):
"""
这个是为了获取url的域名,这个代码对只获取网络请求没用,
"""
res = urlparse(url)
netloc_orig = res.netloc
if str(netloc_orig)[0:3] == "www":
netloc = str(netloc_orig).replace(str(netloc_orig)[0:4], "")
else:
netloc = str(netloc_orig)
return netloc


def info(url):
"""
调用selenium,开启selenium的日志收集功能,收集所有日志,并从中挑出network部分,分析格式化数据,传出
:param url:
:return:
"""
chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--disable-gpu')
# chrome_options.add_argument('--headless')
chrome_options.add_experimental_option('w3c', False)
caps = {
'browserName': 'chrome',
'loggingPrefs': {
'browser': 'ALL',
'driver': 'ALL',
'performance': 'ALL',
},
'goog:chromeOptions': {
'perfLoggingPrefs': {
'enableNetwork': True,
},
'w3c': False,
},
}
driver = webdriver.Chrome(desired_capabilities=caps, chrome_options=chrome_options)
driver.get(url)
# 开始加载网页资源,加载时间设置为20s,防止时间不够用
print('sleep for loading pdf.....')
for si in range(12):
time.sleep(1)
print("sleep for "+str(si))
# time.sleep(3) # 睡眠的作用是等待网页加载完毕,因为还有异步加载的网页,有时候会少拿到请求

# 开始进行翻页,自动点击下一页
element=driver.find_element_by_id('next')
ele_pagen=driver.find_element_by_id('pageNumber').get_attribute("max")
for pgn in range(1,int(ele_pagen)+1):
element.click()
# 停留等待时间
time.sleep(0.2)
print(str(pgn)+'/'+str(ele_pagen))



# 加载后读取log,并进行分析提取



requests = []
response = []
# tlog=driver.get_log('performance')

for log in driver.get_log('performance'):
x = json.loads(log['message'])['message']
if x["method"] == "Network.responseReceived":

# 根据id获取response_body

requestId = x['params']['requestId']

try:
# 重中之重,截取应答的内容,reponse
# 出现类似状况,一定在这里进行操作,操作resBody
response_body = driver.execute_cdp_cmd('Network.getResponseBody',{'requestId': requestId})

# print(response_body['body'])
resBody=response_body['body']

except:

# print('response.body is null')
resBody=''


try:
ip = x["params"]["response"]["remoteIPAddress"]
except BaseException as p:
# print(p)
ip = ""
try:
port = x["params"]["response"]["remotePort"]
except BaseException as f:
# print(f)
port = ""
response.append(
[
x["params"]["response"]["url"],
ip,
port,
x["params"]["response"]["status"],
x["params"]["response"]["statusText"],
x["params"]["type"],
resBody
]
)
elif x["method"] == "Network.requestWillBeSent":
requests.append(
[
x["params"]["request"]["url"],
x["params"]["initiator"]["type"],
x["params"]["request"]["method"],
x["params"]["type"]
]
)
else:
pass
newlist = []
for iqurl in requests:
qwelist = [iqurl]
for ipurl in response:
if iqurl[0] == ipurl[0]:
qwelist.append(ipurl)
else:
pass
newlist.append(qwelist)
for ipurl in response:
p = 0
for i in newlist:
if len(i) == 1:
pass
else:
if ipurl == i[1]:
p += 1
else:
pass
if p == 0:
newlist.append(ipurl)
else:
pass
return_list = []
for a in newlist:
dic = {
"url": "",
"method": "",
"status": "",
"statusText": "",
"type": "",
"initiator": "",
"netloc": "",
"remoteIPAddress": "",
"remotePort": "",
"resbody":""

}
if len(a) == 2:
dic["url"] = a[0][0]
dic["initiator"] = a[0][1]
dic["method"] = a[0][2]
dic["type"] = a[0][3]
dic["netloc"] = netloc_info(a[0][0])
dic["remoteIPAddress"] = a[1][1]
dic["remotePort"] = a[1][2]
dic["status"] = a[1][3]
dic["statusText"] = a[1][4]
dic['resbody']=a[1][6]
return_list.append(dic)
elif len(a) == 1:
if len(a[0]) == 4:
dic["url"] = a[0][0]
dic["netloc"] = netloc_info(a[0][0])
dic["initiator"] = a[0][1]
dic["method"] = a[0][2]
dic["type"] = a[0][3]
return_list.append(dic)
elif len(a[0]) == 6:
dic["url"] = a[0][0]
dic["netloc"] = netloc_info(a[0][0])
dic["remoteIPAddress"] = a[0][1]
dic["remotePort"] = a[0][2]
dic["status"] = a[0][3]
dic["statusText"] = a[0][4]
dic["type"] = a[0][5]
dic["resbody"]=a[0][6]
return_list.append(dic)
else:
pass
else:
pass
driver.close()
driver.quit()
return return_list


def aq_x():

pass


if __name__ == "__main__":
import os,base64
url="file:///E:/xxxxx/file.html"
req_list=info(url)
ii=0
bimg=time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
for reqUrl in req_list:
if reqUrl['url'].startswith('blob'):
ii+=1
# print(reqUrl['url'])
img_str = reqUrl['resbody']
img_url="picx\\"+bimg+"_"+str(ii)+'.jpg'
img_data = base64.b64decode(img_str)
# 注意:如果是"data:image/jpg:base64,",那你保存的就要以png格式,如果是"data:image/png:base64,"那你保存的时候就以jpg格式。
with open(img_url, 'wb') as f:
f.write(img_data)
print(img_url)
pass

饮水思源