but the error occurred.
I also want to know what optimization is.
''' def csv_reader(url_obj): reader = csv.DictReader(url_obj, delimiter=',') for line in reader: print(line["SN"],line["Title"],line["URL"]), URL = line["URL"] site = line["Title"] browser = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options) browser.get(URL) time.sleep(3) # First url input part if browser.find_element_by_xpath("""//*[@id="id"]"""): browser.find_element_by_xpath("""//*[@id="id"]""").send_keys("test") time.sleep(3) # Seconds url input part elif browser.find_element_by_xpath("""//*[@id="uid"]"""): browser.find_element_by_xpath("""//*[@id="uid"]""").send_keys("test") time.sleep(3) else : pass
My results are as follows.
Traceback (most recent call last): File "C:\source\se.py", line 63, in csv_reader(url_obj) File "C:\source\se.py", line 31, in csv_reader if browser.find_element_by_xpath("""//*[@id="id"]"""): File "C:\Users\m4gic\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath return self.find_element(by=By.XPATH, value=xpath) File "C:\Users\m4gic\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element return self.execute(Command.FIND_ELEMENT, { File "C:\Users\m4gic\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\m4gic\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="id"]"} (Session info: chrome=91.0.4472.124)
Why are you using if and else for multiple URL's, in that case if URL list increases you will have to write infinite if and else.
You can have xpath written in csv file as well for different URL and I believe it will be different for all the URL's :
Sample code :
def csv_reader(url_obj):
reader = csv.DictReader(url_obj, delimiter=',')
for line in reader:
print(line["SN"], line["Title"], line["URL"]),
URL = line["URL"]
site = line["Title"]
xpath = line["Xpath"]
browser = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
browser.get(URL)
time.sleep(3)
# First url input part
if len(browser.find_elements_by_xpath(f"{xpath}") > 0 :
browser.find_element_by_xpath(f"{xpath}").send_keys("test")
time.sleep(3)
else:
pass