-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathwebFunctions.py
1747 lines (1379 loc) · 63.8 KB
/
webFunctions.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
import sys
import codecs
try:
import cchardet as chardet
except ImportError:
import chardet as chardet
import http.client
import email.parser
import http.client
import email.parser
cchardet = False
try:
import cchardet
except ImportError:
pass
def isUTF8Strict(data):
'''
Check if all characters in a bytearray are decodable
using UTF-8.
'''
try:
decoded = data.decode('UTF-8')
except UnicodeDecodeError:
return False
else:
for ch in decoded:
if 0xD800 <= ord(ch) <= 0xDFFF:
return False
return True
def decode_headers(header_list):
'''
Decode a list of headers.
Takes a list of bytestrings, returns a list of unicode strings.
The character set for each bytestring is individually decoded.
'''
decoded_headers = []
for header in header_list:
if cchardet:
inferred = cchardet.detect(header)
if inferred and inferred['confidence'] > 0.8:
print("Parsing headers!", header)
decoded_headers.append(header.decode(inferred['encoding']))
else:
decoded_headers.append(header.decode('iso-8859-1'))
else:
# All bytes are < 127 (e.g. ASCII)
if all([char & 0x80 == 0 for char in header]):
decoded_headers.append(header.decode("us-ascii"))
elif isUTF8Strict(header):
decoded_headers.append(header.decode("utf-8"))
else:
decoded_headers.append(header.decode('iso-8859-1'))
return decoded_headers
def parse_headers(fp, _class=http.client.HTTPMessage):
"""Parses only RFC2822 headers from a file pointer.
email Parser wants to see strings rather than bytes.
But a TextIOWrapper around self.rfile would buffer too many bytes
from the stream, bytes which we later need to read as bytes.
So we read the correct bytes here, as bytes, for email Parser
to parse.
Note: Monkey-patched version to try to more intelligently determine
header encoding
"""
headers = []
while True:
line = fp.readline(http.client._MAXLINE + 1)
if len(line) > http.client._MAXLINE:
raise http.client.LineTooLong("header line")
headers.append(line)
if len(headers) > http.client._MAXHEADERS:
raise HTTPException("got more than %d headers" % http.client._MAXHEADERS)
if line in (b'\r\n', b'\n', b''):
break
decoded_headers = decode_headers(headers)
hstring = ''.join(decoded_headers)
return email.parser.Parser(_class=_class).parsestr(hstring)
http.client.parse_headers = parse_headers
import urllib.request
import urllib.parse
import urllib.error
import socks
from sockshandler import SocksiPyHandler
import os.path
import time
import http.cookiejar
import traceback
import multiprocessing
import logging
import zlib
import bs4
import re
import string
import gzip
import string
import io
import socket
import json
import base64
import random
random.seed()
import selenium.webdriver.chrome.service
import selenium.webdriver.chrome.options
import selenium.webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
def as_soup(str):
return bs4.BeautifulSoup(str, "lxml")
class ContentError(urllib.error.URLError):
def __init__(self, reason, errpgcontent):
super().__init__(reason)
self.error_page_content = errpgcontent
def get_error_page(self):
return self.error_page_content
def get_error_page_as_soup(self):
return as_soup(self.error_page_content)
def determine_json_encoding(json_bytes):
'''
Given the fact that the first 2 characters in json are guaranteed to be ASCII, we can use
these to determine the encoding.
See: http://tools.ietf.org/html/rfc4627#section-3
Copied here:
Since the first two characters of a JSON text will always be ASCII
characters [RFC0020], it is possible to determine whether an octet
stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking
at the pattern of nulls in the first four octets.
00 00 00 xx UTF-32BE
00 xx 00 xx UTF-16BE
xx 00 00 00 UTF-32LE
xx 00 xx 00 UTF-16LE
xx xx xx xx UTF-8
'''
assert(isinstance(json_bytes, bytes))
if len(json_bytes) > 4:
b1, b2, b3, b4 = json_bytes[0], json_bytes[1], json_bytes[2], json_bytes[3]
if b1 == 0 and b2 == 0 and b3 == 0 and b4 != 0:
return "UTF-32BE"
elif b1 == 0 and b2 != 0 and b3 == 0 and b4 != 0:
return "UTF-16BE"
elif b1 != 0 and b2 == 0 and b3 == 0 and b4 == 0:
return "UTF-32LE"
elif b1 != 0 and b2 == 0 and b3 != 0 and b4 == 0:
return "UTF-16LE"
elif b1 != 0 and b2 != 0 and b3 != 0 and b4 != 0:
return "UTF-8"
else:
raise ValueError("Unknown encoding!")
elif len(json_bytes) > 2:
b1, b2 = json_bytes[0], json_bytes[1]
if b1 == 0 and b2 == 0:
return "UTF-32BE"
elif b1 == 0 and b2 != 0:
return "UTF-16BE"
elif b1 != 0 and b2 == 0:
raise ValueError("Json string too short to definitively infer encoding.")
elif b1 != 0 and b2 != 0:
return "UTF-8"
else:
raise ValueError("Unknown encoding!")
raise ValueError("Input string too short to guess encoding!")
class title_not_contains(object):
""" An expectation for checking that the title *does not* contain a case-sensitive
substring. title is the fragment of title expected
returns True when the title matches, False otherwise
"""
def __init__(self, title):
self.title = title
def __call__(self, driver):
return self.title not in driver.title
#pylint: disable-msg=E1101, C0325, R0201, W0702, W0703
def wait_for(condition_function):
start_time = time.time()
while time.time() < start_time + 3:
if condition_function():
return True
else:
time.sleep(0.1)
raise Exception(
'Timeout waiting for {}'.format(condition_function.__name__)
)
class load_delay_context_manager(object):
def __init__(self, browser):
self.browser = browser
def __enter__(self):
self.old_page = self.browser.find_element_by_tag_name('html')
def page_has_loaded(self):
new_page = self.browser.find_element_by_tag_name('html')
return new_page.id != self.old_page.id
def __exit__(self, *_):
wait_for(self.page_has_loaded)
class HeadRequest(urllib.request.Request):
def get_method(self):
# Apparently HEAD is now being blocked. Because douche.
return "GET"
# return "HEAD"
class HTTPRedirectBlockerErrorHandler(urllib.request.HTTPErrorProcessor):
def http_response(self, request, response):
code, msg, hdrs = response.code, response.msg, response.info()
# only add this line to stop 302 redirection.
if code == 302:
print("Code!", 302)
return response
if code == 301:
print("Code!", 301)
return response
print("[HTTPRedirectBlockerErrorHandler] http_response! code:", code)
print(hdrs)
print(msg)
if not (200 <= code < 300):
response = self.parent.error('http', request, response, code, msg, hdrs)
return response
https_response = http_response
# Custom redirect handler to work around
# issue https://bugs.python.org/issue17214
class HTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
# Implementation note: To avoid the server sending us into an
# infinite loop, the request object needs to track what URLs we
# have already seen. Do this by adding a handler-specific
# attribute to the Request object.
def http_error_302(self, req, fp, code, msg, headers):
# Some servers (incorrectly) return multiple Location headers
# (so probably same goes for URI). Use first header.
if "location" in headers:
newurl = headers["location"]
elif "uri" in headers:
newurl = headers["uri"]
else:
return
# fix a possible malformed URL
urlparts = urllib.parse.urlparse(newurl)
# For security reasons we don't allow redirection to anything other
# than http, https or ftp.
if urlparts.scheme not in ('http', 'https', 'ftp', ''):
raise urllib.error.HTTPError(
newurl, code,
"%s - Redirection to url '%s' is not allowed" % (msg, newurl),
headers, fp)
if not urlparts.path:
urlparts = list(urlparts)
urlparts[2] = "/"
newurl = urllib.parse.urlunparse(urlparts)
# http.client.parse_headers() decodes as ISO-8859-1. Recover the
# original bytes and percent-encode non-ASCII bytes, and any special
# characters such as the space.
newurl = urllib.parse.quote(
newurl, encoding="iso-8859-1", safe=string.punctuation)
newurl = urllib.parse.urljoin(req.full_url, newurl)
# XXX Probably want to forget about the state of the current
# request, although that might interact poorly with other
# handlers that also use handler-specific request attributes
new = self.redirect_request(req, fp, code, msg, headers, newurl)
if new is None:
return
# loop detection
# .redirect_dict has a key url if url was previously visited.
if hasattr(req, 'redirect_dict'):
visited = new.redirect_dict = req.redirect_dict
if (visited.get(newurl, 0) >= self.max_repeats or
len(visited) >= self.max_redirections):
raise urllib.error.HTTPError(req.full_url, code,
self.inf_msg + msg, headers, fp)
else:
visited = new.redirect_dict = req.redirect_dict = {}
visited[newurl] = visited.get(newurl, 0) + 1
# Don't close the fp until we are sure that we won't use it
# with HTTPError.
fp.read()
fp.close()
return self.parent.open(new, timeout=req.timeout)
# A urllib2 wrapper that provides error handling and logging, as well as cookie management. It's a bit crude, but it works.
# Also supports transport compresion.
# OOOOLLLLLLDDDDD, has lots of creaky internals. Needs some cleanup desperately, but lots of crap depends on almost everything.
# Arrrgh.
from threading import Lock
COOKIEWRITELOCK = Lock()
GLOBAL_COOKIE_FILE = None
class PreemptiveBasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
'''Preemptive basic auth.
Instead of waiting for a 403 to then retry with the credentials,
send the credentials if the url is handled by the password manager.
Note: please use realm=None when calling add_password.'''
def http_request(self, req):
url = req.get_full_url()
realm = None
# this is very similar to the code from retry_http_basic_auth()
# but returns a request object.
user, pw = self.passwd.find_user_password(realm, url)
if pw:
raw = "%s:%s" % (user, pw)
raw = raw.encode("ascii")
auth = b'Basic ' + base64.standard_b64encode(raw).strip()
req.add_unredirected_header(self.auth_header, auth)
return req
https_request = http_request
class WebGetRobust:
COOKIEFILE = 'cookies.lwp' # the path and filename to save your cookies in
cj = None
cookielib = None
opener = None
errorOutCount = 2
# retryDelay = 0.1
retryDelay = 0.0
data = None
# if test=true, no resources are actually fetched (for testing)
# creds is a list of 3-tuples that gets inserted into the password manager.
# it is structured [(top_level_url1, username1, password1), (top_level_url2, username2, password2)]
def __init__(self, test=False, creds=None, logPath="Main.Web", cookie_lock=None, cloudflare=False, use_socks=False, alt_cookiejar=None):
self.rules = {}
self.rules['cloudflare'] = cloudflare
if cookie_lock:
self.cookie_lock = cookie_lock
else:
self.cookie_lock = COOKIEWRITELOCK
self.pjs_driver = None
self.cr_driver = None
self.use_socks = use_socks
# Override the global default socket timeout, so hung connections will actually time out properly.
socket.setdefaulttimeout(15)
self.log = logging.getLogger(logPath)
# print("Webget init! Logpath = ", logPath)
if creds:
print("Have creds for a domain")
if test:
self.log.warning("-----------------------------------------------------------------------------------------------")
self.log.warning("WARNING: WebGet in testing mode!")
self.log.warning("-----------------------------------------------------------------------------------------------")
# Due to general internet people douchebaggyness, I've basically said to hell with it and decided to spoof a whole assortment of browsers
# It should keep people from blocking this scraper *too* easily
self.browserHeaders = getUserAgent()
self.testMode = test # if we don't want to actually contact the remote server, you pass a string containing
# pagecontent for testing purposes as test. It will get returned for any calls of getpage()
self.data = urllib.parse.urlencode(self.browserHeaders)
if creds:
print("Have credentials, installing password manager into urllib handler.")
passManager = urllib.request.HTTPPasswordMgrWithDefaultRealm()
for url, username, password in creds:
passManager.add_password(None, url, username, password)
self.credHandler = PreemptiveBasicAuthHandler(passManager)
else:
self.credHandler = None
self.alt_cookiejar = alt_cookiejar
self.loadCookies()
def loadCookies(self):
if self.alt_cookiejar is not None:
self.alt_cookiejar.init_agent(new_headers=self.browserHeaders)
self.cj = self.alt_cookiejar
else:
self.cj = http.cookiejar.LWPCookieJar() # This is a subclass of FileCookieJar
# that has useful load and save methods
if self.cj is not None:
if os.path.isfile(self.COOKIEFILE):
try:
self.cj.load(self.COOKIEFILE)
# self.log.info("Loading CookieJar")
except:
self.log.critical("Cookie file is corrupt/damaged?")
try:
os.remove(self.COOKIEFILE)
except FileNotFoundError:
pass
if http.cookiejar is not None:
# self.log.info("Installing CookieJar")
self.log.debug(self.cj)
cookieHandler = urllib.request.HTTPCookieProcessor(self.cj)
args = (cookieHandler, HTTPRedirectHandler)
if self.credHandler:
print("Have cred handler. Building opener using it")
args += (self.credHandler, )
if self.use_socks:
print("Using Socks handler")
args = (SocksiPyHandler(socks.SOCKS5, "127.0.0.1", 9050), ) + args
self.opener = urllib.request.build_opener(*args)
#self.opener.addheaders = [('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')]
self.opener.addheaders = self.browserHeaders
#urllib2.install_opener(self.opener)
for cookie in self.cj:
self.log.debug(cookie)
#print cookie
def chunkReport(self, bytesSoFar, totalSize):
if totalSize:
percent = float(bytesSoFar) / totalSize
percent = round(percent * 100, 2)
self.log.info("Downloaded %d of %d bytes (%0.2f%%)" % (bytesSoFar, totalSize, percent))
else:
self.log.info("Downloaded %d bytes" % (bytesSoFar))
def chunkRead(self, response, chunkSize=2 ** 18, reportHook=None):
contentLengthHeader = response.info().getheader('Content-Length')
if contentLengthHeader:
totalSize = contentLengthHeader.strip()
totalSize = int(totalSize)
else:
totalSize = None
bytesSoFar = 0
pgContent = ""
while 1:
chunk = response.read(chunkSize)
pgContent += chunk
bytesSoFar += len(chunk)
if not chunk:
break
if reportHook:
reportHook(bytesSoFar, chunkSize, totalSize)
return pgContent
def getSoup(self, *args, **kwargs):
if 'returnMultiple' in kwargs and kwargs['returnMultiple']:
raise ValueError("getSoup cannot be called with 'returnMultiple' being true")
if 'soup' in kwargs and kwargs['soup']:
raise ValueError("getSoup contradicts the 'soup' directive!")
page = self.getpage(*args, **kwargs)
if isinstance(page, bytes):
raise ValueError("Received content not decoded! Cannot parse!")
soup = as_soup(page)
return soup
def getJson(self, *args, **kwargs):
if 'returnMultiple' in kwargs and kwargs['returnMultiple']:
raise ValueError("getSoup cannot be called with 'returnMultiple' being true")
attempts = 0
while 1:
try:
page = self.getpage(*args, **kwargs)
if isinstance(page, bytes):
page = page.decode(determine_json_encoding(page))
# raise ValueError("Received content not decoded! Cannot parse!")
page = page.strip()
ret = json.loads(page)
return ret
except ValueError:
if attempts < 1:
attempts += 1
self.log.error("JSON Parsing issue retreiving content from page!")
for line in traceback.format_exc().split("\n"):
self.log.error("%s", line.rstrip())
self.log.error("Retrying!")
# Scramble our current UA
self.browserHeaders = getUserAgent()
if self.alt_cookiejar:
self.cj.init_agent(new_headers=self.browserHeaders)
time.sleep(self.retryDelay)
else:
self.log.error("JSON Parsing issue, and retries exhausted!")
# self.log.error("Page content:")
# self.log.error(page)
# with open("Error-ctnt-{}.json".format(time.time()), "w") as tmp_err_fp:
# tmp_err_fp.write(page)
raise
def resetUa(self):
if self.pjs_driver != None:
self.pjs_driver.quit()
self.pjs_driver = None
if not self.pjs_driver:
self._initPjsWebDriver()
self._syncIntoPjsWebDriver()
self.browserHeaders = getUserAgent()
if self.alt_cookiejar:
self.cj.init_agent(new_headers=self.browserHeaders)
def getFileAndName(self, *args, **kwargs):
if 'returnMultiple' in kwargs:
raise ValueError("getFileAndName cannot be called with 'returnMultiple'")
if 'soup' in kwargs and kwargs['soup']:
raise ValueError("getFileAndName contradicts the 'soup' directive!")
kwargs["returnMultiple"] = True
pgctnt, pghandle = self.getpage(*args, **kwargs)
info = pghandle.info()
if not 'Content-Disposition' in info:
hName = ''
elif not 'filename=' in info['Content-Disposition']:
hName = ''
else:
hName = info['Content-Disposition'].split('filename=')[1]
return pgctnt, hName
def buildRequest(self, pgreq, postData, addlHeaders, binaryForm, req_class = urllib.request.Request):
# Encode Unicode URL's properly
try:
tmp = pgreq.encode("ascii")
except UnicodeEncodeError:
print("Wat?")
print("pgreq: '%s'", pgreq)
try:
params = {}
headers = {}
if postData != None:
self.log.info("Making a post-request! Params: '%s'", postData)
params['data'] = urllib.parse.urlencode(postData).encode("utf-8")
if addlHeaders != None:
self.log.info("Have additional GET parameters!")
for key, parameter in addlHeaders.items():
self.log.info(" Item: '%s' -> '%s'", key, parameter)
headers = addlHeaders
if binaryForm:
self.log.info("Binary form submission!")
if 'data' in params:
raise ValueError("You cannot make a binary form post and a plain post request at the same time!")
params['data'] = binaryForm.make_result()
headers['Content-type'] = binaryForm.get_content_type()
headers['Content-length'] = len(params['data'])
return req_class(pgreq, headers=headers, **params)
except:
self.log.critical("Invalid header or url")
raise
def decodeHtml(self, pageContent, cType):
# this *should* probably be done using a parser.
# However, it seems to be grossly overkill to shove the whole page (which can be quite large) through a parser just to pull out a tag that
# should be right near the page beginning anyways.
# As such, it's a regular expression for the moment
# Regex is of bytes type, since we can't convert a string to unicode until we know the encoding the
# bytes string is using, and we need the regex to get that encoding
coding = re.search(rb"charset=[\'\"]?([a-zA-Z0-9\-]*)[\'\"]?", pageContent, flags=re.IGNORECASE)
cType = b""
charset = None
try:
if coding:
cType = coding.group(1)
codecs.lookup(cType.decode("ascii"))
charset = cType.decode("ascii")
except LookupError:
# I'm actually not sure what I was thinking when I wrote this if statement. I don't think it'll ever trigger.
if (b";" in cType) and (b"=" in cType): # the server is reporting an encoding. Now we use it to decode the
dummy_docType, charset = cType.split(b";")
charset = charset.split(b"=")[-1]
if not charset:
self.log.warning("Could not find encoding information on page - Using default charset. Shit may break!")
charset = "iso-8859-1"
try:
pageContent = str(pageContent, charset)
except UnicodeDecodeError:
self.log.error("Encoding Error! Stripping invalid chars.")
pageContent = pageContent.decode('utf-8', errors='ignore')
return pageContent
def decompressContent(self, coding, pgctnt):
#preLen = len(pgctnt)
if coding == 'deflate':
compType = "deflate"
pgctnt = zlib.decompress(pgctnt, -zlib.MAX_WBITS)
elif coding == 'gzip':
compType = "gzip"
buf = io.BytesIO(pgctnt)
f = gzip.GzipFile(fileobj=buf)
pgctnt = f.read()
elif coding == "sdch":
raise ValueError("Wait, someone other then google actually supports SDCH compression?")
else:
compType = "none"
return compType, pgctnt
def getItem(self, itemUrl):
try:
content, handle = self.getpage(itemUrl, returnMultiple=True)
except:
print("Failure?")
if self.rules['cloudflare']:
if not self.stepThroughCloudFlare(itemUrl, titleNotContains='Just a moment...'):
raise ValueError("Could not step through cloudflare!")
# Cloudflare cookie set, retrieve again
content, handle = self.getpage(itemUrl, returnMultiple=True)
else:
raise
if not content or not handle:
raise urllib.error.URLError("Failed to retreive file from page '%s'!" % itemUrl)
fileN = urllib.parse.unquote(urllib.parse.urlparse(handle.geturl())[2].split("/")[-1])
fileN = bs4.UnicodeDammit(fileN).unicode_markup
mType = handle.info()['Content-Type']
# If there is an encoding in the content-type (or any other info), strip it out.
# We don't care about the encoding, since WebFunctions will already have handled that,
# and returned a decoded unicode object.
if mType and ";" in mType:
mType = mType.split(";")[0].strip()
# *sigh*. So minus.com is fucking up their http headers, and apparently urlencoding the
# mime type, because apparently they're shit at things.
# Anyways, fix that.
if '%2F' in mType:
mType = mType.replace('%2F', '/')
self.log.info("Retreived file of type '%s', name of '%s' with a size of %0.3f K", mType, fileN, len(content)/1000.0)
return content, fileN, mType
def _initPjsWebDriver(self):
if self.pjs_driver:
self.pjs_driver.quit()
dcap = dict(DesiredCapabilities.PHANTOMJS)
wgSettings = dict(self.browserHeaders)
# Install the headers from the WebGet class into phantomjs
dcap["phantomjs.page.settings.userAgent"] = wgSettings.pop('User-Agent')
for headerName in wgSettings:
if headerName != 'Accept-Encoding':
dcap['phantomjs.page.customHeaders.{header}'.format(header=headerName)] = wgSettings[headerName]
self.pjs_driver = selenium.webdriver.PhantomJS(desired_capabilities=dcap)
self.pjs_driver.set_window_size(1280, 1024)
def _initCrWebDriver(self):
if self.cr_driver:
self.cr_driver.quit()
dcap = dict(DesiredCapabilities.CHROME)
wgSettings = dict(self.browserHeaders)
# Install the headers from the WebGet class into phantomjs
user_agent = wgSettings.pop('User-Agent')
dcap["chrome.page.settings.userAgent"] = user_agent
for headerName in wgSettings:
if headerName != 'Accept-Encoding':
dcap['chrome.page.customHeaders.{header}'.format(header=headerName)] = wgSettings[headerName]
dcap["chrome.switches"] = ["--user-agent="+user_agent]
chromedriver = r'./venv/bin/chromedriver'
chrome = r'./Headless/headless_shell'
chrome_options = selenium.webdriver.chrome.options.Options()
chrome_options.binary_location = chrome
chrome_options.add_argument('--load-component-extension')
chrome_options.add_argument("--user-agent=\"{}\"".format(user_agent))
chrome_options.add_argument('--verbose')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-extension')
self.cr_driver = selenium.webdriver.Chrome(chrome_options=chrome_options, desired_capabilities=dcap)
# We can't set the chrome desired capabilities, since headless chrome
# doesn't allow extensions.
self.cr_driver.set_page_load_timeout(30)
def _syncIntoPjsWebDriver(self):
# TODO
pass
def _syncOutOfPjsWebDriver(self):
for cookie in self.pjs_driver.get_cookies():
self.addSeleniumCookie(cookie)
def getItemPhantomJS(self, itemUrl):
self.log.info("Fetching page for URL: '%s' with PhantomJS" % itemUrl)
if not self.pjs_driver:
self._initPjsWebDriver()
self._syncIntoPjsWebDriver()
with load_delay_context_manager(self.pjs_driver):
self.pjs_driver.get(itemUrl)
time.sleep(3)
fileN = urllib.parse.unquote(urllib.parse.urlparse(self.pjs_driver.current_url)[2].split("/")[-1])
fileN = bs4.UnicodeDammit(fileN).unicode_markup
self._syncOutOfPjsWebDriver()
# Probably a bad assumption
mType = "text/html"
# So, self.pjs_driver.page_source appears to be the *compressed* page source as-rendered. Because reasons.
source = self.pjs_driver.execute_script("return document.getElementsByTagName('html')[0].innerHTML")
assert source != '<head></head><body></body>'
source = "<html>"+source+"</html>"
return source, fileN, mType
def decodeTextContent(self, pgctnt, cType):
if cType:
if (";" in cType) and ("=" in cType):
# the server is reporting an encoding. Now we use it to decode the content
# Some wierdos put two charsets in their headers:
# `text/html;Charset=UTF-8;charset=UTF-8`
# Split, and take the first two entries.
docType, charset = cType.split(";")[:2]
charset = charset.split("=")[-1]
# Only decode content marked as text (yeah, google is serving zip files
# with the content-disposition charset header specifying "UTF-8") or
# specifically allowed other content types I know are really text.
decode = ['application/atom+xml', 'application/xml', "application/json", 'text']
if any([item in docType for item in decode]):
try:
pgctnt = str(pgctnt, charset)
except UnicodeDecodeError:
self.log.error("Encoding Error! Stripping invalid chars.")
pgctnt = pgctnt.decode('utf-8', errors='ignore')
else:
# The server is not reporting an encoding in the headers.
# Use content-aware mechanisms for determing the content encoding.
if "text/html" in cType or \
'text/javascript' in cType or \
'text/css' in cType or \
'application/xml' in cType or \
'application/atom+xml' in cType: # If this is a html/text page, we want to decode it using the local encoding
pgctnt = self.decodeHtml(pgctnt, cType)
elif "text/plain" in cType or "text/xml" in cType:
pgctnt = bs4.UnicodeDammit(pgctnt).unicode_markup
# Assume JSON is utf-8. Probably a bad idea?
elif "application/json" in cType:
pgctnt = pgctnt.decode('utf-8')
elif "text" in cType:
self.log.critical("Unknown content type!")
self.log.critical(cType)
else:
self.log.critical("No content disposition header!")
self.log.critical("Cannot guess content type!")
return pgctnt
def retreiveContent(self, pgreq, pghandle, callBack):
try:
# If we have a progress callback, call it for chunked read.
# Otherwise, just read in the entire content.
if callBack:
pgctnt = self.chunkRead(pghandle, 2 ** 17, reportHook=callBack)
else:
pgctnt = pghandle.read()
if pgctnt == None:
return False
self.log.info("URL fully retrieved.")
preDecompSize = len(pgctnt)/1000.0
encoded = pghandle.headers.get('Content-Encoding')
compType, pgctnt = self.decompressContent(encoded, pgctnt)
decompSize = len(pgctnt)/1000.0
# self.log.info("Page content type = %s", type(pgctnt))
cType = pghandle.headers.get("Content-Type")
if compType == 'none':
self.log.info("Compression type = %s. Content Size = %0.3fK. File type: %s.", compType, decompSize, cType)
else:
self.log.info("Compression type = %s. Content Size compressed = %0.3fK. Decompressed = %0.3fK. File type: %s.", compType, preDecompSize, decompSize, cType)
pgctnt = self.decodeTextContent(pgctnt, cType)
return pgctnt
except:
print("pghandle = ", pghandle)
self.log.error(sys.exc_info())
traceback.print_exc()
self.log.error("Error Retrieving Page! - Transfer failed. Waiting %s seconds before retrying", self.retryDelay)
try:
self.log.critical("Critical Failure to retrieve page! %s at %s", pgreq.get_full_url(), time.ctime(time.time()))
self.log.critical("Exiting")
except:
self.log.critical("And the URL could not be printed due to an encoding error")
print()
self.log.error(pghandle)
time.sleep(self.retryDelay)
return False
# HUGE GOD-FUNCTION.
# OH GOD FIXME.
# postData expects a dict
# addlHeaders also expects a dict
def getpage(self, requestedUrl, **kwargs):
# pgreq = fixurl(pgreq)
# strip trailing and leading spaces.
requestedUrl = requestedUrl.strip()
# addlHeaders = None, returnMultiple = False, callBack=None, postData=None, soup=False, retryQuantity=None, nativeError=False, binaryForm=False
# If we have 'soup' as a param, just pop it, and call `getSoup()`.
if 'soup' in kwargs and kwargs['soup']:
self.log.warn("'soup' kwarg is depreciated. Please use the `getSoup()` call instead.")
kwargs.pop('soup')
return self.getSoup(requestedUrl, **kwargs)
# Decode the kwargs values
addlHeaders = kwargs.setdefault("addlHeaders", None)
returnMultiple = kwargs.setdefault("returnMultiple", False)
callBack = kwargs.setdefault("callBack", None)
postData = kwargs.setdefault("postData", None)
retryQuantity = kwargs.setdefault("retryQuantity", None)
nativeError = kwargs.setdefault("nativeError", False)
binaryForm = kwargs.setdefault("binaryForm", False)
# Conditionally encode the referrer if needed, because otherwise
# urllib will barf on unicode referrer values.
if addlHeaders and 'Referer' in addlHeaders:
addlHeaders['Referer'] = iri2uri(addlHeaders['Referer'])
requestedUrl = iri2uri(requestedUrl)
if not self.testMode:
retryCount = 0
while 1:
pgctnt = None
pghandle = None
pgreq = self.buildRequest(requestedUrl, postData, addlHeaders, binaryForm)
errored = False
lastErr = ""
retryCount = retryCount + 1
if (retryQuantity and retryCount > retryQuantity) or (not retryQuantity and retryCount > self.errorOutCount):
self.log.error("Failed to retrieve Website : %s at %s All Attempts Exhausted", pgreq.get_full_url(), time.ctime(time.time()))
pgctnt = None
try:
self.log.critical("Critical Failure to retrieve page! %s at %s, attempt %s", pgreq.get_full_url(), time.ctime(time.time()), retryCount)
self.log.critical("Error: %s", lastErr)
self.log.critical("Exiting")
except:
self.log.critical("And the URL could not be printed due to an encoding error")
break
#print "execution", retryCount
try:
# print("Getpage!", requestedUrl, kwargs)
pghandle = self.opener.open(pgreq, timeout=30) # Get Webpage
# print("Gotpage")
except urllib.error.HTTPError as e: # Lotta logging
self.log.warning("Error opening page: %s at %s On Attempt %s.", pgreq.get_full_url(), time.ctime(time.time()), retryCount)
self.log.warning("Error Code: %s", e)
#traceback.print_exc()
lastErr = e