1"""
2This module defines the `main()` coroutine for the Apify Actor, executed from the `__main__.py` file.
3
4Feel free to modify this file to suit your specific needs.
5
6To build Apify Actors, utilize the Apify SDK toolkit, read more at the official documentation:
7https://docs.apify.com/sdk/python
8"""
9
10from urllib.parse import urljoin
11from time import sleep
12
13from selenium import webdriver
14from selenium.webdriver.chrome.options import Options as ChromeOptions
15from selenium.webdriver.common.by import By
16
17from apify import Actor
18
19
20
21
22
23
24async def main() -> None:
25 """
26 The main coroutine is being executed using `asyncio.run()`, so do not attempt to make a normal function
27 out of it, it will not work. Asynchronous execution is required for communication with Apify platform,
28 and it also enhances performance in the field of web scraping significantly.
29 """
30
31 async with Actor:
32
33 actor_input = await Actor.get_input() or {}
34 start_urls = actor_input.get('start_urls', [
35 {'url': 'https://knowledge.alteryx.com/index/s/article/How-to-restart-Alteryx-Service-remotely-when-RDP-is-not-available'}
36 ])
37 max_depth = actor_input.get('max_depth', 1)
38 wait_time = actor_input.get('wait_time_in_seconds', 5)
39 cookies = actor_input.get('cookies', [])
40 if not isinstance(wait_time, int):
41 Actor.log.info('Sleep time is not a number. Setting default...')
42 wait_time = 5
43
44 if not start_urls:
45 Actor.log.info('No start URLs specified in actor input, exiting...')
46 await Actor.exit()
47
48
49 default_queue = await Actor.open_request_queue()
50 for start_url in start_urls:
51 url = start_url.get('url')
52 Actor.log.info(f'Enqueuing {url} ...')
53 await default_queue.add_request({'url': url, 'userData': {'depth': 0}})
54
55
56 Actor.log.info('Launching Chrome WebDriver...')
57 chrome_options = ChromeOptions()
58 if Actor.config.headless:
59 chrome_options.add_argument('--headless')
60 chrome_options.add_argument('--no-sandbox')
61 chrome_options.add_argument('--disable-dev-shm-usage')
62 driver = webdriver.Chrome(options=chrome_options)
63
64
65 driver.get('http://www.example.com')
66 assert driver.title == 'Example Domain'
67
68
69 Actor.log.debug(f"Num of cookies to add: {len(cookies)}")
70 for cookie in cookies:
71 driver.add_cookie(cookie)
72
73
74 driver.refresh()
75
76
77 while request := await default_queue.fetch_next_request():
78 url = request['url']
79 depth = request['userData']['depth']
80 Actor.log.info(f'Scraping {url} ...')
81
82 try:
83
84 driver.get(url)
85 Actor.log.info(f'Sleeping for this much time: {wait_time} seconds ...')
86 sleep(wait_time)
87
88
89 title = driver.title
90 html_content = driver.page_source
91 Actor.log.info("Got title and html content")
92 await Actor.push_data({'url': url, 'title': title, 'text': html_content})
93 except Exception:
94 Actor.log.exception(f'Cannot extract data from {url}.')
95 finally:
96 await default_queue.mark_request_as_handled(request)
97
98 driver.quit()