How to iterate multiple elements in single loop using python selenium -
below code working fine using multiple loops.is possible make 1 loop data.
multiple loop code:
for post in driver.find_elements_by_class_name("_1uozlx"): mobile_link += [ post.get_attribute("href") ] post1 in driver.find_elements_by_class_name("_3wu53n"): mobile_name += [ post1.text ] post2 in driver.find_elements_by_css_selector("._1vc4oe._2rq-nk"): offer_price += [ post2.text ]
full code:
from selenium import webdriver selenium.webdriver.support.ui import webdriverwait selenium.webdriver.support import expected_conditions ec selenium.common.exceptions import timeoutexception selenium.webdriver.common.by import import time import csv chrome_path = r"c:\users\venkatesh\appdata\local\programs\python\python35\chromedriver.exe" driver = webdriver.chrome(chrome_path) regionidarray = ["https://www.flipkart.com/mobiles/pr?otracker=categorytree&page=1&sid=tyy%2c4io", "https://www.flipkart.com/mobiles/pr?otracker=categorytree&page=2&sid=tyy%2c4io"] mobile_link = [] mobile_name = [] offer_price = [] actual_price = [] data_list=[] delay = 10 # seconds reg in regionidarray: try: driver.get(reg) webdriverwait(driver, delay).until(ec.presence_of_element_located((by.xpath, "//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div/div[1]"))) driver.execute_script("window.scrollto(0, document.body.scrollheight);") print("page ready") post in driver.find_elements_by_class_name("_1uozlx"): mobile_link += [ post.get_attribute("href") ] post1 in driver.find_elements_by_class_name("_3wu53n"): mobile_name += [ post1.text ] post2 in driver.find_elements_by_css_selector("._1vc4oe._2rq-nk"): offer_price += [ post2.text ] time.sleep(10) except timeoutexception: print("loading took time") driver.quit()
it's still multiple loops, it's bit neater list comprehensions:
mobile_link += [ post.get_attribute("href") post in driver.find_elements_by_class_name("_1uozlx") ] mobile_name += [ post1.text post1 in driver.find_elements_by_class_name("_3wu53n") ] offer_price += [ post2.text post2 in driver.find_elements_by_css_selector("._1vc4oe._2rq-nk") ]
what reason wanting single loop? seems unrelated elements.
Comments
Post a Comment