Repository navigation
Expand file tree
/
Copy pathselenium_example.py
More file actions
95 lines (78 loc) · 3.51 KB
/
Copy pathselenium_example.py
File metadata and controls
95 lines (78 loc) · 3.51 KB
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
"""Selenium: scrape the listing pages in headless Chrome through a proxy.
Chrome's --proxy-server flag has no place for a username and password, so the
example starts a local relay (proxy_relay.py) that adds them and points Chrome
at the relay. Selenium itself reads the fields with find_elements.
python examples/selenium_example.py --pages 2
Selenium 4.6+ downloads a matching ChromeDriver on first run (Selenium
Manager). Chrome must be installed.
"""
import os
import sys
from typing import List, Optional, Sequence, Tuple
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from books_site import Book, parse_args, parse_price, print_books, rating_from_classes, write_csv
from proxy_config import describe, load_dotenv_if_present, proxy_source_from_env
from proxy_relay import ProxyRelay
def make_driver(proxy_server: str, headless: bool = True, extra_arguments: Sequence[str] = ()) -> webdriver.Chrome:
options = webdriver.ChromeOptions()
if headless:
options.add_argument("--headless=new")
options.add_argument(f"--proxy-server={proxy_server}")
for argument in extra_arguments:
options.add_argument(argument)
return webdriver.Chrome(options=options)
def parse(driver: webdriver.Chrome) -> Tuple[List[Book], Optional[str]]:
"""Read the books from the page the browser has open."""
books = []
for pod in driver.find_elements(By.CSS_SELECTOR, "article.product_pod"):
link = pod.find_element(By.CSS_SELECTOR, "h3 a")
rating = pod.find_element(By.CSS_SELECTOR, "p.star-rating").get_attribute("class")
books.append(
Book(
title=link.get_attribute("title"),
price=parse_price(pod.find_element(By.CSS_SELECTOR, "p.price_color").text),
rating=rating_from_classes(rating.split()),
in_stock="In stock" in pod.find_element(By.CSS_SELECTOR, "p.availability").text,
# The href property (not the attribute) is already absolute.
url=link.get_property("href"),
)
)
try:
next_url = driver.find_element(By.CSS_SELECTOR, "li.next a").get_property("href")
except NoSuchElementException:
next_url = None
return books, next_url
def scrape(
start_url: str, pages: int, proxy_url: str, headless: bool = True, extra_arguments: Sequence[str] = ()
) -> List[Book]:
books: List[Book] = []
with ProxyRelay(proxy_url) as relay:
driver = make_driver(relay.url, headless=headless, extra_arguments=extra_arguments)
try:
url: Optional[str] = start_url
for _ in range(pages):
if url is None:
break
driver.get(url)
page_books, url = parse(driver)
books.extend(page_books)
finally:
driver.quit()
return books
def main() -> None:
args = parse_args(__doc__.splitlines()[0])
load_dotenv_if_present()
source = proxy_source_from_env(proxy_type=args.proxy_type)
print("Proxy:", describe(source))
# One browser, one proxy: a datacenter list gives the next IP in the list.
books = scrape(args.start_url, args.pages, source.next())
print(f"Scraped {len(books)} books from {args.pages} page(s):")
print_books(books)
if args.csv:
write_csv(books, args.csv)
print("Saved to", args.csv)
if __name__ == "__main__":
main()