summaryrefslogtreecommitdiffstats
path: root/libdscrpr/generic_scrapers/selenium_scraper.py
blob: 4d4f7437d1544eac4c003e6427f53b3bc10ffdd3 (plain)
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
# -*- coding: utf-8 -*-
#
# Copyright 2020-2021 Michael Buesch <m@bues.ch>
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

from libdscrpr.generic_scrapers.base import *
from libdscrpr.util.string import *

from selenium import webdriver
from selenium.common.exceptions import WebDriverException, TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
import contextlib

__all__ = [
    "SeleniumScraperError",
    "SeleniumScraper",
    "WebDriverException",
]

class SeleniumScraperError(ScraperBaseError):
    pass

class SeleniumScraper(ScraperBase):
    """Selenium engine scraper base.
    """

    def __init__(self, tls=True, **kwargs):
        #TODO tls
        super().__init__(**kwargs)
        self.__drv = None

    def setup(self):
        super().setup()
        if self.__drv is None:
            wdOptions = webdriver.chrome.options.Options()
            wdOptions.headless = self.headless
            drv = webdriver.Chrome(options=wdOptions)

            self.__defaultWait = 10
            drv.implicitly_wait(self.__defaultWait)
            drv.set_page_load_timeout(30)
            drv.set_script_timeout(30)

            drv.delete_all_cookies()

            if not self.headless:
                drv.maximize_window()

            self.__drv = drv

    def shutdown(self):
        if self.__drv is not None:
            with contextlib.suppress(Exception):
                self.__drv.close()
            self.__drv = None
        super().shutdown()

    def _wait(self, wait, timeout=10):
        """Wait for a given wait object to return True.
        """
        if self.__drv is None:
            raise SeleniumScraperError("Setup not done.")
        try:
            self.__drv.implicitly_wait(timeout)
            w = WebDriverWait(self.__drv, timeout)
            w.until(wait)
        except TimeoutException as e:
            return False
        finally:
            self.__drv.implicitly_wait(self.__defaultWait)
        return True

    def _findElem(self, xpath):
        """Find an element by XPath.
        """
        if self.__drv is None:
            raise SeleniumScraperError("Setup not done.")
        return self.__drv.find_element_by_xpath(xpath)

    def _findElems(self, xpath):
        """Find elements by XPath.
        """
        if self.__drv is None:
            raise SeleniumScraperError("Setup not done.")
        return self.__drv.find_elements_by_xpath(xpath)

    def _getElemClickable(self, xpath, timeout=10, quiet=False):
        """Get a clickable element by XPath (e.g. button).
        """
        if self.__drv is None:
            raise SeleniumScraperError("Setup not done.")
        try:
            self.__drv.implicitly_wait(timeout)
            w = WebDriverWait(self.__drv, timeout)
            elem = w.until(EC.element_to_be_clickable((By.XPATH, xpath)))
        except TimeoutException as e:
            if not quiet:
                print(f"Timeout waiting for '{xpath}':\n{e}")
            return None
        finally:
            self.__drv.implicitly_wait(self.__defaultWait)
        return elem

    def _getActionChains(self):
        """Make a new ActionChains instance.
        """
        if self.__drv is None:
            raise SeleniumScraperError("Setup not done.")
        return ActionChains(self.__drv)

    def loadPage(self, url):
        """Send a GET request to an URL.
        """
        if self.__drv is None:
            raise SeleniumScraperError("Setup not done.")
        self.__drv.get(url)

    def getPageSource(self):
        """Get the source text of the current page.
        """
        if self.__drv is None:
            raise SeleniumScraperError("Setup not done.")
        return self.__drv.page_source

    def clickElem(self, xpath, timeout=10, quiet=False):
        """Click onto an element defined by XPath.
        """
        if self.__drv is None:
            raise SeleniumScraperError("Setup not done.")
        elem = self._getElemClickable(xpath, timeout=timeout, quiet=quiet)
        if not elem:
            raise SeleniumScraperError(f"Failed to click '{xpath}'")
        elem.click()

    def fillInput(self, xpath, text, clear=True, enter=False, timeout=10):
        """Fill an input box defined by XPath.
        """
        if self.__drv is None:
            raise SeleniumScraperError("Setup not done.")
        elem = self.__drv.find_element_by_xpath(xpath)
        if not elem:
            raise SeleniumScraperError(f"Failed to fill input element '{xpath}'")
        if clear:
            elem.clear()
        if text:
            elem.send_keys(text)
        if enter:
            elem.send_keys(Keys.ENTER)

    def waitUntilExists(self, xpath, timeout=10):
        """Wait until an element with the specified XPath exists.
        """
        if self.__drv is None:
            raise SeleniumScraperError("Setup not done.")
        def waiter(drv):
            return bool(drv.find_element_by_xpath(xpath))
        if not self._wait(waiter, timeout):
            raise SeleniumScraperError(f"Failed to wait for element '{xpath}'")

    def waitUntilSourceText(self, text, timeout=10):
        """Wait until the specified text fragment appears in the source text.
        """
        if self.__drv is None:
            raise SeleniumScraperError("Setup not done.")
        def waiter(drv):
            return text in drv.page_source
        if not self._wait(waiter, timeout):
            raise SeleniumScraperError(f"Failed to wait for source text '{text}'")

    def dump(self, filename):
        """Dump the current source text to a file.
        """
        if self.__drv is None:
            raise SeleniumScraperError("Setup not done.")
        with open(filename, "wb") as f:
            f.write(self.getPageSource().encode("UTF-8", "ignore"))

    def screenshot(self, filename):
        """Dump a screenshot to a file.
        """
        if self.__drv is None:
            raise SeleniumScraperError("Setup not done.")
        self.__drv.save_screenshot(filename)

# vim: ts=4 sw=4 expandtab
bues.ch cgit interface