Repository navigation
Expand file tree
/
Copy pathVersion 2
More file actions
152 lines (80 loc) · 2.58 KB
/
Copy pathVersion 2
File metadata and controls
152 lines (80 loc) · 2.58 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
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
# Version 2: Here you manually enter XPath of each page. Change conditions of the code according to your requirements.
from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from openpyxl import Workbook
# Chrome Setup
options = Options()
options.add_argument("--ignore-certificate-errors")
options.add_argument("--test-type")
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(
service=ChromeService(ChromeDriverManager().install()),
options=options
)
driver.get("Enter your URL")
driver.maximize_window()
wait = WebDriverWait(driver,20)
# Excel Setup
excel_file_path = r"Enter Excel file path.xlsx"
workbook = Workbook()
workbook.save(excel_file_path)
page_number = 0
while page_number < 100:
try:
data_boxes = wait.until(
EC.presence_of_all_elements_located(
(By.CLASS_NAME,"card-view")
)
)
sheet_name = f"Data_{page_number + 1}"
sheet = workbook.create_sheet(
title=sheet_name
)
extracted_data = []
for box in data_boxes:
title = (
box.find_element(By.CLASS_NAME,"title")
.find_element(By.TAG_NAME,"span")
.text.strip()
)
value = (
box.find_element(By.CLASS_NAME,"value")
.find_element(By.TAG_NAME,"span")
.text.strip()
)
extracted_data.append(
[title,value]
)
for row in extracted_data:
sheet.append(row)
workbook.save(excel_file_path)
print(
f"Page {page_number + 1} saved successfully"
)
driver.execute_script(
"window.scrollTo(0,document.body.scrollHeight)"
)
next_xpath = input(
f"Enter XPath for page {page_number + 2}: "
)
next_button = wait.until(
EC.presence_of_element_located(
(By.XPATH,next_xpath)
)
)
next_button.click()
time.sleep(5)
page_number += 1
except Exception as error:
print(
f"Error: {error}"
)
break
print("Scraping Completed")
driver.quit()