-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode
80 lines (65 loc) · 2.56 KB
/
code
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
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome()
driver.get(url="https://www.1mg.com/")
# Close the city update modal if it exists
try:
update_modal = driver.find_element(By.XPATH,
"//div[@class='UpdateCityModal_update-btn_2qmN1 UpdateCityModalbtn__oMW5n']")
update_modal.click()
time.sleep(10)
except:
pass
# Wait for the search results to load
time.sleep(2)
# Search for multivitamins
search_bar = driver.find_element(By.XPATH, "//input[@id='srchBarShwInfo']")
search_bar.send_keys("Multivitamins")
# Click the search button
search_button = driver.find_element(By.XPATH, "//div[@class='header_search_icon']")
search_button.click()
# Wait for the product boxes to load
time.sleep(5)
# Extract and print brand names
product_boxes = driver.find_elements(By.XPATH, "//div[@class='style__product-box___3oEU6']")
for product_box in product_boxes:
print("--------------------------")
# Use a try-except block to handle StaleElementReferenceException
try:
# Open the product in a new tab
product_url = product_box.find_element(By.XPATH, ".//a").get_attribute("href")
driver.execute_script("window.open('" + product_url + "', 'new tab');")
time.sleep(2)
# Switch to the newly opened tab
driver.switch_to.window(driver.window_handles[1])
# Gather information
try:
brand_name = driver.find_element(By.XPATH, "//h1").text
print("Brand:", brand_name)
except:
print("Not available")
try:
cost = driver.find_element(By.XPATH, "//span[@class='PriceBoxPlanOption__offer-price___3v9x8 PriceBoxPlanOption__offer-price-cp___2QPU_']").text
print("Cost:", cost)
except:
print("Not available")
try:
rating = driver.find_element(By.XPATH, "//span[@class='RatingDisplay__ratings-header___ZNj5b']").text
print("Rating:", rating)
except:
print("Not available")
try:
tablet_count = driver.find_element(By.XPATH,
"//span[@class='PackSizeLabel__single-packsize___3KEr_']").text
print("No of tablets:", tablet_count)
except:
print("Not available")
# Close the tab
driver.close()
# Switch back to the main window
driver.switch_to.window(driver.window_handles[0])
except Exception as e:
print("Exception occurred:", e)
# Close the browser
driver.quit()