forked from kiorky/spynner
/
browser.py
1743 lines (1535 loc) · 67.1 KB
/
browser.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/python
# Copyright (c) Arnau Sanchez <tokland@gmail.com>
# This script is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this software. If not, see <http://www.gnu.org/licenses/>
"""
Spynner is a stateful programmatic web-browser module for Python with
Javascript/AJAX support. It is build upon the PyQtWebKit framework.
"""
import itertools
import cookielib
import tempfile
from pprint import pprint
import urlparse
import urllib2
import time
import sys
import re
import os
from StringIO import StringIO
import pkg_resources
import autopy
try:
from PySide import QtCore
QtCore.QString = str
from PySide.QtCore import SIGNAL, QUrl, QString, Qt, QEvent
from PySide.QtCore import QSize, QDateTime, QPoint
from PySide.QtGui import QApplication, QImage, QPainter
from PySide.QtGui import QCursor, QMouseEvent, QKeyEvent
from PySide.QtNetwork import QNetworkCookie, QNetworkAccessManager, QSslConfiguration, QSslCipher
from PySide.QtNetwork import QNetworkCookieJar, QNetworkRequest, QNetworkProxy, QSsl, QSslSocket
from PySide.QtWebKit import QWebPage, QWebView
HAS_PYSIDE = True
except Exception, e:
HAS_PYSIDE = False
from PyQt4 import QtCore
from PyQt4.QtCore import SIGNAL, QUrl, QString, Qt, QEvent
from PyQt4.QtCore import QSize, QDateTime, QPoint
from PyQt4.QtGui import QApplication, QImage, QPainter
from PyQt4.QtGui import QCursor, QMouseEvent, QKeyEvent
from PyQt4.QtNetwork import QNetworkCookie, QNetworkAccessManager, QSslConfiguration, QSslCipher
from PyQt4.QtNetwork import QNetworkCookieJar, QNetworkRequest, QNetworkProxy, QSsl, QSslSocket
from PyQt4.QtWebKit import QWebPage, QWebView
from PyQt4.QtWebKit import QWebInspector
SpynnerQapplication = None
# Debug levels
ERROR, WARNING, INFO, DEBUG = range(4)
argv = ['dummy']
_marker = []
class Browser(object):
"""
Stateful programmatic web browser class based upon QtWebKit.
"""
errorCode = None
errorMessage = None
_javascript_directories = [
pkg_resources.resource_filename('spynner', 'javascript'),
]
_jquery = 'jquery-1.5.2.js'
_jquery_simulate = 'jquery.simulate.js'
def __init__(self,
qappargs=None,
debug_level=ERROR,
want_compat=False,
embed_jquery=False,
embed_jquery_simulate=False,
additional_js_files = None,
jslib = None,
download_directory = ".",
user_agent = None,
debug_stream = sys.stderr,
event_looptime = 0.01 ,
ignore_ssl_errors = True,
headers = None,
ssl_protocol=None,
ssl_ciphers = None,
inspector=False,
):
"""
Init a Browser instance.
@param qappargs: Arguments for QApplication constructor.
@param debug_level: Debug level logging (L{ERROR} by default)
@param want_compat: set jquery compatiblity mode to "self.jslib"
@param jslib: IF True: Use jQuery.noConflict to "jslib", else just use '$'
@param download_directory: Directory where downloaded files will be stored.
@param user_agent User agent for requests (see QWebPage::userAgentForUrl for details)
@param event_looptime Event loop dispatcher loop delay (seconds).
@apram ignore_ssl_errors If True, ignore SSL certificate errors.
@param debug_stream File-like stream where debug output will be written.
@param headers (list of tuple) http headers to send with every request
@param ssl_protocol SSL protocol to force use of:
QSsl.SslV3
QSsl.SslV2
QSsl.TlsV1
QSsl.UnknownProtocol
QSsl.AnyProtocol
QSsl.TlsV1SslV3
QSsl.SecureProtocols
Important vars:
- self.webpage: QwebPage object
- self.application : QApplication object
- self.webframe: active QWebFrame object
- self.manager: QNetworkAccessManager object
- self.files: represent a list of dicts tracking downloaded files where the download key
is the path, each entry is in the form {'reply': replyobj, 'req': reqobj}
"""
self.download_directory = download_directory
import spynner
self.ssl_protocol = ssl_protocol
self.sslconf = QSslConfiguration.defaultConfiguration()
ciphers = []
self.ssl_ciphers = ssl_ciphers
if not self.ssl_ciphers:
self.ssl_ciphers = []
for cip in self.sslconf.ciphers():
if (
(toString(cip.name()) in self.ssl_ciphers)
or not self.ssl_ciphers
):
ciphers.append(cip)
self.sslconf.setCiphers(ciphers)
if not spynner.SpynnerQapplication:
spynner.SpynnerQapplication = QApplication(spynner.argv)
self.application = spynner.SpynnerQapplication
self.want_compat = want_compat
self.embed_jquery = embed_jquery
self.embed_jquery_simulate = embed_jquery_simulate
self.debug_stream = debug_stream
self.user_agent = user_agent
# self._headers is just internal
# to manager.create_request
# as we cant change the useragent
# directly via the adequat http header (qwebframe
# will overwrite it later)
self.headers = headers
self._headers = []
if self.headers is None:
self.headers = []
if self.user_agent:
self.headers.append(('User-Agent', self.user_agent))
self.additional_js_files = additional_js_files
self.additional_js = ""
self.event_looptime = event_looptime
self.ignore_ssl_errors = ignore_ssl_errors
"""PyQt4.QtWebKit.QWebPage object."""
wp = self.webpage = QWebPage()
# Network Access Manager and cookies
#mngr = self.manager = QNetworkAccessManager()
mngr = self.manager = NManager.new(self)
"""PyQt4.QtNetwork.QTNetworkAccessManager object."""
self.webpage.setNetworkAccessManager(self.manager)
if not self.additional_js_files:
self.additional_js_files = []
self.jslib = jslib
if not self.want_compat:
if jslib is None:
self.jslib = '$'
else:
self.jslib = jslib
else:
self.jslib = 'spynnerjq'
self.debug_level = debug_level
"""PyQt4.QtWebKit.QWebFrame main webframe object."""
self.webview = None
"""PyQt4.QtWebKit.QWebView object."""
self._url_filter = None
self._webframe = None
self._html_parser = None
self.files = []
# Javascript
directory = _first(self._javascript_directories, os.path.isdir)
if not directory:
raise SpynnerError("Cannot find javascript directory: %s" %
self._javascript_directories)
self.jquery = open(os.path.join(directory, self._jquery)).read()
self.jquery_simulate = open(os.path.join(directory, self._jquery_simulate)).read()
for fn in self.additional_js_files:
if not os.path.exists(fn):
fn = os.path.join(directory, fn)
self.additional_js += "\n%s" % open(fn).read()
wp.javaScriptAlert = self._javascript_alert
wp.javaScriptConsoleMessage = self._javascript_console_message
wp.javaScriptConfirm = self._javascript_confirm
wp.javaScriptPrompt = self._javascript_prompt
self._javascript_confirm_callback = None
self._javascript_confirm_prompt = None
"""PyQt4.QtNetwork.QNetworkCookieJar object."""
self.cookies = []
mngr.sslErrors.connect(self._on_manager_ssl_errors)
mngr.finished.connect(self._on_reply)
mngr.authenticationRequired.connect(
self._on_authentication_required)
self._operation_names = dict(
(getattr(QNetworkAccessManager, s + "Operation", s),
s.lower())
for s in ("Get", "Head", "Post",
"Put", "Delete", "Custom"))
for i in self._operation_names.keys():
if isinstance(i, basestring):
del self._operation_names[i]
# Webpage slots
self._load_status = None
self._replies = 0
wp.setForwardUnsupportedContent(True)
wp.unsupportedContent.connect(
self._on_unsupported_content)
wp.loadFinished.connect(self._on_load_finished)
wp.loadStarted.connect(self._on_load_started)
if inspector:
self.inspector = QWebInspector()
self.inspector.setPage(self.webpage)
self.inspector.setVisible(True)
@property
def webframe(self):
"""PyQt4.QtNetwork.QWebFrame object."""
if self._webframe is None:
self.setframe_obj()
return self._webframe
def _events_loop(self, wait=None):
if wait is None:
wait = self.event_looptime
self.application.processEvents()
time.sleep(wait)
def _on_load_started(self):
self._load_status = None
self._debug(INFO, "Page load started")
def _on_manager_ssl_errors(self, reply, errors):
url = unicode(toString(reply.url()))
if self.ignore_ssl_errors:
self._debug(WARNING, "SSL certificate error ignored: %s" % url)
reply.ignoreSslErrors()
else:
self._debug(WARNING, "SSL certificate error: %s" % url)
def _on_authentication_required(self, reply, authenticator):
url = unicode(toString(reply.url()))
realm = unicode(authenticator.realm())
self._debug("HTTP auth required: %s (realm: %s)" % (url, realm))
if not self._http_authentication_callback:
self._debug(WARNING, "HTTP auth required, but no callback defined")
return
credentials = self._http_authentication_callback(url, realm)
if credentials:
user, password = credentials
self._debug(INFO, "callback returned HTTP credentials: %s/%s" %
(user, "*"*len(password)))
authenticator.setUser(user)
authenticator.setPassword(password)
else:
self._debug(WARNING, "HTTP auth callback returned no credentials")
def _on_reply(self, reply):
self._replies += 1
self._reply_url = unicode(toString(reply.url()))
self._reply_status = not bool(reply.error())
self.cookies = merge_cookies(
self.cookies,
self.manager.cookieJar().allCookies())
try:
http_status = "%s" % toString(
reply.attribute(QNetworkRequest.HttpStatusCodeAttribute))
http_status_m = "%s" % toString(
reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute))
except:
http_status_m, http_status = "", ""
if reply.error():
self._debug(WARNING, "Reply error: %s/%s %s - %d (%s)" %
(http_status, http_status_m,
self._reply_url, reply.error(), reply.errorString()))
self.errorCode = reply.error()
self.errorMessage = reply.errorString()
else:
self._debug(INFO, "Reply: %s/%s - %s" % (
http_status, http_status_m, self._reply_url))
for header in reply.rawHeaderList():
self._debug(DEBUG, " %s: %s" % (header, reply.rawHeader(header)))
def _on_unsupported_content(self, reply, outfd=None):
if not reply.error():
self._start_download(reply, outfd)
else:
self._debug(ERROR, "Error on unsupported content: %s" % reply.errorString())
def _javascript_alert(self, webframe, message):
self._debug(INFO, "Javascript alert: %s" % message)
if self.webview:
QWebPage.javaScriptAlert(self.webpage, webframe, message)
def _javascript_console_message(self, message, line, sourceid):
if line:
self._debug(INFO, "Javascript console (%s:%d): %s" %
(sourceid, line, message))
else:
self._debug(INFO, "Javascript console: %s" % message)
def _javascript_confirm(self, webframe, message):
smessage = unicode(message)
url = webframe.url()
self._debug(INFO, "Javascript confirm (webframe url = %s): %s" %
(url, smessage))
if self._javascript_confirm_callback:
value = self._javascript_confirm_callback(url, smessage)
self._debug(INFO, "Javascript confirm callback returned %s" % value)
return value
return QWebPage.javaScriptConfirm(self.webpage, webframe, message)
def _javascript_prompt(self, webframe, message, defaultvalue, result):
url = webframe.url()
smessage = unicode(message)
self._debug(INFO, "Javascript prompt (webframe url = %s): %s" %
(url, smessage))
if self._javascript_prompt_callback:
value = self._javascript_prompt_callback(url, smessage, defaultvalue)
self._debug(INFO, "Javascript prompt callback returned: %s" % value)
if value in (False, None):
return False
result.clear()
result.append(value)
return True
return QWebPage.javaScriptPrompt(self.webpage, webframe, message,
defaultvalue, result)
def _on_webview_destroyed(self, window):
self.webview = None
def _on_load_finished(self, successful):
if hasattr(self, "webpage"):
self.setframe_obj()
self._load_status = successful
status = {True: "successful", False: "error"}[successful]
self._debug(INFO, "Page load finished (%d bytes): %s (%s)" %
(len(self.html), self.url, status))
def _get_filepath_for_url(self, url, reply=None):
urlinfo = urlparse.urlsplit(url)
path = os.path.join(os.path.abspath(self.download_directory), urlinfo.netloc)
if urlinfo.path != '/':
p = urlinfo.path
if len(p) > 2:
if p[0] == '/':
p = p[1:]
path = os.path.join(path, p)
if reply.hasRawHeader('content-disposition'):
cd = '%s' % reply.rawHeader('content-disposition')
pattern = 'attachment;filename=(.*)'
if re.match(pattern, cd):
filename = re.sub('attachment;filename=(.*)', '\\1', cd)
path = os.path.join(path, filename)
if not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
if path is None:
raise SpynnerError('Download mode is unknown, can\'t determine the final filename')
return path
def _start_download(self, reply, outfd):
url = unicode(toString(reply.url()))
path = None
if outfd is None:
path = self._get_filepath_for_url(url, reply)
outfd = open(path, "wb")
def _on_ready_read():
data = reply.readAll()
if getattr(reply, 'downloaded_nbytes', None) is None:
reply.downloaded_nbytes= 0
reply.downloaded_nbytes += len(data)
outfd.write(data)
self._debug(DEBUG, "Read from download stream (%d bytes): %s"
% (len(data), url))
def _on_network_error():
self._debug(ERROR, "Network error on download: %s" % url)
def _on_finished():
data = reply.readAll()
if len(data):
if getattr(reply, 'downloaded_nbytes at end', None) is None:
reply.downloaded_nbytes= 0
reply.downloaded_nbytes += len(data)
outfd.write(data)
self._debug(DEBUG, "Read from download stream at end (%d bytes): %s"
% (len(data), url))
suf = ''
if path is not None:
outfd.flush()
dict(self.files)[path]['finished'] = True
suf = ' in {0}'.format(path)
self._debug(INFO, "Download finished: {0}{1}".format(url, path))
if path is not None:
self.files.append((path, {'reply':reply,
'readed': False,
'finished':False,}))
reply.readyRead.connect(_on_ready_read)
reply.error.connect(_on_network_error)
reply.finished.connect(_on_finished)
self._debug(INFO, "Start download: %s" % url)
def _wait_load(self, timeout=None):
self._events_loop(0.0)
if self._load_status is not None:
load_status = self._load_status
self._load_status = None
return load_status
itime = time.time()
while self._load_status is None:
if timeout and time.time() - itime > timeout:
raise SpynnerTimeout("Timeout reached: %d seconds" % timeout)
self._events_loop()
self._events_loop(0.0)
if self._load_status:
self.load_js()
self.webpage.setViewportSize(self.webpage.mainFrame().contentsSize())
load_status = self._load_status
self._load_status = None
return load_status
def _debug(self, level, *args):
if level <= self.debug_level:
kwargs = dict(outfd=self.debug_stream)
_debug(*args, **kwargs)
def get_js_obj_length(self, res):
if res.type() != res.Map:
return False
resmap = res.toMap()
lenfield = QString(u'length')
if lenfield not in resmap:
return False
if resmap[lenfield].type() == resmap[lenfield].Double:
return int(resmap[lenfield].toDouble()[0])
else:
return resmap[lenfield].toInt()[0]
def jslen(self, selector):
res = self.runjs("%s('%s')" % (self.jslib, selector))
return self.get_js_obj_length(res)
def _runjs_on_jquery(self, name, code):
res = self.runjs(code)
if not isinstance(self.get_js_obj_length(res), int):
raise SpynnerJavascriptError("error on %s: %s" % (name, code))
return res
def _get_html(self):
return unicode(self.webframe.toHtml())
def _get_soup(self):
if not self._html_parser:
raise SpynnerError("Cannot get soup with no HTML parser defined")
return self._html_parser(self.html)
def _get_url(self):
return unicode(toString(self.webframe.url()))
url = property(_get_url)
"""Current URL."""
contents = property(_get_html)
"""Rendered HTML in current page."""
html = property(_get_html)
"""Rendered HTML in current page."""
soup = property(_get_soup)
"""HTML soup (see L{set_html_parser})."""
def load(self,
url,
load_timeout=10,
wait_callback = None,
tries=None,
operation=QNetworkAccessManager.GetOperation,
body=None,
headers=None
):
"""Load a web page and return status (a boolean).
@param url url to open
@param headers http headers tuples
eg: [('User-Agent', 'foo')]
@param url url to open
@param body request body (string)
@param operation one of:
QNetworkAccessManager.HeadOperation
QNetworkAccessManager.GetOperation
QNetworkAccessManager.PutOperation
QNetworkAccessManager.PostOperation
QNetworkAccessManager.DeleteOperation
QNetworkAccessManager.CustomOperation
@param load_timeout timeout to load the page, or if you use wait_callback, time between retries
@param wait_callback a callback to test if content is ready
@param tries set to True for unlimited retries, to int for limited to tries, tries.
eg:
Open google
>>> br.load('http://www.google.fr')
Same thing except we will try to see if there is 'google' in the html,
thus with 3 wills at 10 seconds of interval
>>> def wait_load(b):
... return 'google' in b.html.lower()
>>> br.load('http://www.google.fr', wait_callback=wait_load, tries=3)
"""
if not headers:
headers = []
if not body:
body = ""
self._headers = self.headers[:]
self._headers.extend(headers)
req = self.make_request(url)
self.webframe.load(req, operation, body)
if wait_callback is None:
return self._wait_load(timeout = load_timeout)
else:
return self.wait_for_content(wait_callback, tries=tries, delay=load_timeout)
def make_request(self, url, operation="GET"):
if operation:
operation = ("%s" % operation).lower()
if isinstance(url, basestring):
url = QUrl(url)
if not isinstance(url, QNetworkRequest):
url = QNetworkRequest(url)
for header, value in self._headers:
url.setRawHeader(header, value)
url = self.apply_ssl(url)
return url
def apply_ssl(self, request):
if self.ssl_protocol:
if self.sslconf.protocol() != self.ssl_protocol:
self.sslconf.setProtocol(self.ssl_protocol)
QSslConfiguration.setDefaultConfiguration(self.sslconf)
request.setSslConfiguration(self.sslconf)
return request
def is_jquery_loaded(self):
return toString(self.runjs('typeof(spynner_jquery_loaded);', debug=False)) != 'undefined'
def is_jquery_simulate_loaded(self):
return toString(
self.runjs('typeof(spynner_jquery_simulate_loaded);', debug=False)) != 'undefined'
def is_additional_js_loaded(self):
return toString(
self.runjs('typeof(spynner_additional_js_loaded);', debug=False)) != 'undefined'
def load_jquery(self, force=False):
"""Load jquery in the current frame"""
jscode = ''
if self.embed_jquery or force:
if not self.is_jquery_loaded():
jscode += self.jquery
if self.want_compat or (self.jslib != '$'):
jscode += "\nvar %s = jQuery.noConflict();" % self.jslib
jscode += "var spynner_jquery_loaded = 1 ;"
self.runjs(jscode, debug=False)
def load_js(self):
self.load_jquery()
self.load_jquery_simulate()
self.load_additional_js()
def load_jquery_simulate(self, force=False):
"""Load jquery simulate in the current frame"""
if self.embed_jquery_simulate or force:
if not self.is_jquery_simulate_loaded():
self.runjs(self.jquery_simulate, debug=False)
self.runjs("var spynner_jquery_simulate_loaded = 1 ;", debug=False)
def load_additional_js(self, force=False):
"""Load jquery in the current frame"""
if not self.is_additional_js_loaded() or force:
if len(self.additional_js.strip()) > 0:
self.runjs(self.additional_js, debug=False)
self.runjs("var spynner_additional_js_loaded = 1 ;", debug=False)
def wait_a_little(br, timeout):
try:
br.wait_load(timeout)
except SpynnerTimeout, e:
pass
def wait_requests(self, wait_requests = None, url = None, url_regex = None):
if wait_requests:
while self._replies < wait_requests:
self._events_loop()
self._events_loop(0.0)
if url_regex or url:
last_replies = self._replies
while True:
if last_replies != self._replies:
if url_regex:
if re.search(url_regex, self._reply_url):
break
elif url:
if url == self._reply_url:
break
self._events_loop()
self._events_loop(0.0)
def sendText(self, selector, text, keyboard_modifiers = Qt.NoModifier, wait_load=False, wait_requests=None, timeout=None):
"""
Send text in any element (to fill it for example)
@param selector: QtWebkit Selector
@param keys to input in the QT way
@param wait_load: If True, it will wait until a new page is loaded.
@param timeout: Seconds to wait for the page to load before raising an exception.
@param wait_requests: How many requests to wait before returning. Useful for AJAX requests.
>>> br.sendText('#val_cel_dentifiant', 'fancy text')
"""
element = self.webframe.findFirstElement(selector)
element.setFocus()
eventp = QKeyEvent(QEvent.KeyPress, Qt.Key_A, keyboard_modifiers, QString(text))
self.application.sendEvent(self.webview, eventp)
self._events_loop(timeout)
self.wait_requests(wait_requests)
if wait_load:
return self._wait_load(timeout)
def sendKeys(self, selector, keys, keyboard_modifiers = Qt.NoModifier, wait_load=False, wait_requests=None, timeout=None):
"""
Click any clickable element in page.
see http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qt.html#Key-enum
@param selector: jQtWebkit Selector
@param keys to input in the QT way
@param wait_load: If True, it will wait until a new page is loaded.
@param timeout: Seconds to wait for the page to load before
raising an exception.
@param wait_requests: How many requests to wait before returning. Useful
for AJAX requests.
Send raw keys:
>>> br.sendKeys('#val_cel_dentifiant', [Qt.Key_A,Qt.Key_A,Qt.Key_C,]
"""
element = self.webframe.findFirstElement(selector)
element.setFocus()
for key in keys:
eventp = QKeyEvent(QEvent.KeyPress, key, keyboard_modifiers)
self.application.sendEvent(self.webview, eventp)
self._events_loop(timeout)
self.wait_requests(wait_requests)
if wait_load:
return self._wait_load(timeout)
def click(self, selector, wait_load=False, wait_requests=None, timeout=None):
"""
Click any clickable element in page.
@param selector: jQuery selector.
@param wait_load: If True, it will wait until a new page is loaded.
@param timeout: Seconds to wait for the page to load before
raising an exception.
@param wait_requests: How many requests to wait before returning. Useful
for AJAX requests.
By default this method will not wait for a page to load.
If you are clicking a link or submit button, you must call this
method with C{wait_load=True} or, alternatively, call
L{wait_load} afterwards. However, the recommended way it to use
L{click_link}.
When a non-HTML file is clicked this method will download it. The
file is automatically saved keeping the original structure (as
wget --recursive does). For example, a file with URL
I{http://server.org/dir1/dir2/file.ext} will be saved to
L{download_directory}/I{server.org/dir1/dir2/file.ext}.
"""
if not self.embed_jquery_simulate:
return self.wk_click(selector,
wait_load=wait_load,
wait_requests=wait_requests,
timeout=timeout)
jscode = "%s('%s').simulate('click');" % (self.jslib, selector)
self._replies = 0
self._runjs_on_jquery("click", jscode)
self.wait_requests(wait_requests)
if wait_load:
return self._wait_load(timeout)
def click_link(self, selector, timeout=None):
"""Click a link and wait for the page to load."""
return self.click(selector, wait_load=True, timeout=timeout)
def click_ajax(self, selector, wait_requests=1, timeout=None):
"""Click a AJAX link and wait for the request to finish."""
return self.click(selector, wait_requests=wait_requests, timeout=timeout)
def move_mouse(self, selector, timeout=1, offsetx=0, offsety=0, real=True):
"""Move the move to the css selector"""
self.moveMouse(
self.getPosition(
selector,
offsetx=offsetx, offsety=offsety),
timeout=timeout,
real=real)
def moveMouse(self, where, timeout=1, real=False,
offsetx=0, offsety=0,
adapt_size=False, pdb=False):
"""Move the mouse to a relative to the window point."""
if adapt_size:
time.sleep(1)
if not real:
where = self.getRealPosition(where)
where = QPoint(int(where.x())+offsetx,
int(where.y())+offsety)
self.webview.grabMouse()
#self._events_loop(timeout)
#cursorw = self.application.desktop().cursor()
cursorw = QCursor()
cursorw.setPos(where)
self.webview.releaseMouse()
#self._events_loop(timeout)
return cursorw
def getRealPosition(self, point, offsetx=0, offsety=0):
"""Compute the coordinates by merging with the containing frame.
@param point: (QPoint)
"""
rect = self.webframe.geometry()
where = QPoint(rect.x() + point.x() + offsetx,
rect.y() + point.y() + offsety)
where = self.webview.mapToGlobal(where)
return where
def nativeClickAt(self, where, timeout=1, real=False, pdb=False):
"""Click on an arbitrar location of the browser.
@param where: where to click (QPoint)
@param real: if not true coordinates are relative to the window instead of the screen
@timeout seconds: seconds to wait after click
"""
if not real:
where = self.getRealPosition(where)
self.moveMouse(where, timeout=timeout, real=True, pdb=pdb)
"""do not work anymore, rely on autopy
def click():
in the meantime
w = self.webview.page()
buttons = Qt.MouseButtons(Qt.LeftButton)
eventp = QMouseEvent(QEvent.MouseButtonPress, where,
Qt.LeftButton, buttons, Qt.NoModifier)
eventl = QMouseEvent(QEvent.MouseButtonRelease, where,
Qt.LeftButton, buttons, Qt.NoModifier)
f.application.sendEvent(w, eventp)
self.application.sendEvent(w, eventl)
self._events_loop(0)
self._events_loop(0)
self.application.processEvents()
self.application.processEvents()"""
autopy.mouse.click()
try:
self._events_loop(0.05)
self._events_loop(0.05)
except:
pass
def getPosition(self, selector, offsetx=0, offsety=0):
"""Get the position QPoint(x,y) of a css selector.
@param selector: The css Selector to query against
"""
jscode = "off = %s('%s').offset(); off.left+','+off.top" % (self.jslib, selector)
self._replies = 0
try:
item = self.webframe.findFirstElement(selector)
geo = item.geometry()
twhere = geo.topLeft()
twhere = QPoint(int(twhere.x()) + offsetx,
int(twhere.y()) + offsety)
where = self.webview.mapToGlobal(twhere)
if where == twhere:
where = self.webview.mapToGlobal(where)
except:
#try also using js
try:
x, y = ("%s" % toString(self.runjs(jscode, debug=False))).split(',')
twhere = QPoint(int(x)+offsetx, int(y)+offsety)
where = self.webview.mapToGlobal(twhere)
if where == twhere:
where = self.webview.mapToGlobal(where)
except Exception, e:
raise SpynnerError('Cant find %s (%s)' % (selector, e))
return where
def wk_click_element(self, element, wait_load=False, wait_requests=None, timeout=None):
"""
Click on an element by using raw javascript WebKit.click() method.
@param element: QWebElement object
@param wait_load: If True, it will wait until a new page is loaded.
@param timeout: Seconds to wait for the page to load before
raising an exception.
@param wait_requests: How many requests to wait before returning. Useful
for AJAX requests.
By default this method will not wait for a page to load.
If you are clicking a link or submit button, you must call this
method with C{wait_load=True} or, alternatively, call
L{wait_load} afterwards. However, the recommended way it to use
L{click_link}.
When a non-HTML file is clicked this method will download it. The
file is automatically saved keeping the original structure (as
wget --recursive does). For example, a file with URL
I{http://server.org/dir1/dir2/file.ext} will be saved to
L{download_directory}/I{server.org/dir1/dir2/file.ext}.
"""
#element.evaluateJavaScript("this.click()")
jscode = (
"var e = document.createEvent('MouseEvents');"
"e.initEvent( 'click', true, true );"
"this.dispatchEvent(e);"
)
element.evaluateJavaScript(jscode)
time.sleep(0.5)
self.wait_requests(wait_requests)
if wait_load:
return self._wait_load(timeout)
def wk_click_element_link(self, element, timeout=None):
"""Click a link and wait for the page to load.
@param selector: WebKit xpath selector to an element
@param: timeout timeout to wait in seconds
"""
return self.wk_click_element(element, wait_load=True, timeout=timeout)
def wk_click_element_ajax(self, element, wait_requests=1, timeout=None):
"""Click a AJAX link and wait for the request to finish.
@param selector: WebKit xpath selector to an element
@param wait_requests: How many requests to wait before returning. Useful for AJAX requests.
@param: timeout timeout to wait in seconds
"""
return self.wk_click_element(element, wait_requests=wait_requests, timeout=timeout)
def wk_click(self, selector, wait_load=False, wait_requests=None, timeout=None):
"""
Select an element with a CSS2 selector and then click by using raw javascript WebKit.click() method.
See the wk_click_element functions for additional documentation
@param selector: WebKit selector.
@param wait_load: If True, it will wait until a new page is loaded.
@param timeout: Seconds to wait for the page to load before
raising an exception.
@param wait_requests: How many requests to wait before returning. Useful
for AJAX requests.
"""
element = self.webframe.findFirstElement(selector)
return self.wk_click_element(element, wait_load=wait_load, wait_requests=wait_requests, timeout=timeout)
def wk_click_link(self, selector, timeout=None):
"""Click a link and wait for the page to load.
See the wk_click_element_link functions for additional documentation
@param selector: WebKit xpath selector to an element
@param: timeout timeout to wait in seconds
"""
element = self.webframe.findFirstElement(selector)
return self.wk_click_element_link(element, timeout=timeout)
def wk_click_ajax(self, selector, wait_requests=1, timeout=None):
"""Click a AJAX link and wait for the request to finish.
See the wk_click_element_ajax functions for additional documentation
@param selector: WebKit xpath selector to an element
@param wait_requests: How many requests to wait before returning. Useful
for AJAX requests.
@param: timeout timeout to wait in seconds
"""
element = self.webframe.findFirstElement(selector)
return self.wk_click_element_ajax(element, wait_requests=wait_requests, timeout=timeout)
def native_click(self, selector, wait_load=False, wait_requests=None, timeout=1, offsetx = 5, offsety = 5, real=False, pdb=False):
"""
Click any clickable element in page by sending a raw QT mouse event.
@param selector: jQuery selector.
@param wait_load: If True, it will wait until a new page is loaded.
@param timeout: Seconds to wait for the page to load before
raising an exception.
@param wait_requests: How many requests to wait before returning. Useful
for AJAX requests.
@param offsetx: offset to click on the widget to the top left of it on the X axis (left to right)
@param offsety: offset to click on the widget to the top left of it on the Y axix (top to bottom)
"""
where = self.getPosition(selector)
item = self.webframe.findFirstElement(selector)
item.setFocus()
where = QPoint(where.x() + offsetx, where.y() + offsety)
self.nativeClickAt(where, timeout, real=real, pdb=pdb)
self.wait_requests(wait_requests)
if wait_load:
return self._wait_load(timeout)
def native_click_link(self, selector, timeout=None, offsetx = 0, offsety = 0):
"""Click a link and wait for the page to load using a real mouse event.
@param selector: jQuery selector.
@param timeout: Seconds to wait for the page to load before
raising an exception.
@param offsetx: offset to click on the widget to the top left of it on the X axis (left to right)
@param offsety: offset to click on the widget to the top left of it on the Y axix (top to bottom)
"""
return self.native_click(selector, wait_load=True, timeout=timeout, offsetx=offsetx, offsety=offsety)
def native_click_ajax(self, selector, wait_requests=1, timeout=None, offsetx = 0, offsety = 0):
"""Click a AJAX link using a raw mouse click and wait for the request to finish.
@param selector: jQuery selector.
@param timeout: Seconds to wait for the page to load before
raising an exception.
@param offsetx: offset to click on the widget to the top left of it on the X axis (left to right)
@param offsety: offset to click on the widget to the top left of it on the Y axix (top to bottom)
"""
return self.native_click(selector, wait_requests=wait_requests, timeout=timeout, offsetx=offsetx, offsety=offsety)
def wait_load(self, timeout=None):
"""
Wait until the page is loaded.
@param timeout: Time to wait (seconds) for the page load to complete.
@return: Boolean state
@raise SpynnerTimeout: If timeout is reached.
"""
return self._wait_load(timeout)
def wait_for_content(self, callback, tries=None, error_message=None, delay=5):
"""
Wait until the page is loaded.
@param content: callback that takes the browser as input must return true when suceed
@param timeout: number of retries / True for no limit
@param delay: delay between retries
@param error_message: additional message to set in the error message
@return: Boolean state
@raise SpynnerTimeout: If timeout is reached.
>>> def wait_toto(browser):
... if 'toto' in browser.html:
... return True
... return False
>>> br.wait_for_content(wait_toto)
"""
ref_tries = tries
ret = None
found = False
loaded = False
head = "SPYNNER waitload:"
loaded_msg = (
'%s content loaded, waiting for '
'content to mach the callback' % head)
waiting_msg = (
'%s content not loaded, '
'fallback by waiting' % head)
to_msg = ("%s %s" % (
"%s Timeout reached: " % head,
"%d retries for %ss delay."))
found_msg = (
'%s The callback found what it '
'was waiting for in its contents!' % head)
for_ = "%s FOR: %s" % (
head, error_message)
if not tries:
tries = True
while bool(tries) and not found:
if (
isinstance(tries, int)
and not isinstance(tries, bool)
):
if tries > 0: