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
11
12from selenium import webdriver
13from selenium.webdriver.chrome.options import Options as ChromeOptions
14from selenium.webdriver.common.by import By
15
16from apify import Actor
17
18
19
20
21
22
23async def main() -> None:
24 """
25 The main coroutine is being executed using `asyncio.run()`, so do not attempt to make a normal function
26 out of it, it will not work. Asynchronous execution is required for communication with Apify platform,
27 and it also enhances performance in the field of web scraping significantly.
28 """
29 async with Actor:
30
31 actor_input = await Actor.get_input() or {}
32 start_urls = actor_input.get('start_urls', [{'url': 'https://apify.com'}])
33 max_depth = actor_input.get('max_depth', 1)
34
35 if not start_urls:
36 Actor.log.info('No start URLs specified in actor input, exiting...')
37 await Actor.exit()
38
39
40 default_queue = await Actor.open_request_queue()
41 for start_url in start_urls:
42 url = start_url.get('url')
43 Actor.log.info(f'Enqueuing {url} ...')
44 await default_queue.add_request({'url': url, 'userData': {'depth': 0}})
45
46
47 Actor.log.info('Launching Chrome WebDriver...')
48 chrome_options = ChromeOptions()
49 if Actor.config.headless:
50 chrome_options.add_argument('--headless')
51 chrome_options.add_argument('--no-sandbox')
52 chrome_options.add_argument('--disable-dev-shm-usage')
53 driver = webdriver.Chrome(options=chrome_options)
54
55 driver.get('http://www.example.com')
56 assert driver.title == 'Example Domain'
57
58
59 while request := await default_queue.fetch_next_request():
60 url = request['url']
61 depth = request['userData']['depth']
62 Actor.log.info(f'Scraping {url} ...')
63
64 try:
65
66 driver.get(url)
67
68
69
70 if depth < max_depth:
71 for link in driver.find_elements(By.TAG_NAME, 'a'):
72 link_href = link.get_attribute('href')
73 link_url = urljoin(url, link_href)
74 if link_url.startswith(('http://', 'https://')):
75 Actor.log.info(f'Enqueuing {link_url} ...')
76 await default_queue.add_request({
77 'url': link_url,
78 'userData': {'depth': depth + 1},
79 })
80
81
82 title = driver.title
83 await Actor.push_data({'url': url, 'title': title})
84 except Exception:
85 Actor.log.exception(f'Cannot extract data from {url}.')
86 finally:
87 await default_queue.mark_request_as_handled(request)
88
89 driver.quit()