I have this code, and the error is very silly (I don't think the selenium have anything to do with it), but i've tried a lot of things and nothing works. What can I do?
THE ERROR IS IN THE VARIABLES NAME "sHoras"
class Clima():
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
website = "https://weather.com/?Goto=Redirected"
path = "C:/Users/Administrador/Downloads/chromedriver_win32/chromedriver.exe"
driver = webdriver.Chrome(options=options, service=Service(path))
driver.get(website)
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "truste-button3"))).click()
time.sleep(3)
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'LanguageSelector--LanguageSelectorStatus--mXkYQ'))).click()
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[3]/div[1]/header/div/div[2]/div[2]/nav/div/div/section/div/ul/li[2]'))).click()
time.sleep(3)
button = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'LocationSearch_input')))
time.sleep(2)
button.click()
time.sleep(1)
button.send_keys("Medellin, Antioquia")
button.send_keys(Keys.RETURN)
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[3]/div[3]/div/nav/div/div[1]/a[2]/span'))).click()
time.sleep(2)
temperatura = driver.find_elements(By.XPATH, "//summary/div/div/div/span[#class='DetailsSummary--tempValue--1K4ka']")
temperatura = [temperatura.text for temperatura in temperatura]
horasT = driver.find_elements(By.XPATH, "//div/h3")
horasT = [horasT.text for horasT in horasT]
driver.quit()
indx = datetime.datetime.now()
indx = int(indx.strftime('%H'))
indx = (24 - indx)
sHoras = []
[sHoras.append(hora) for hora in horasT if hora not in sHoras]
horas = []
for i in range(0, indx):
horas.append(sHoras[i])
THE ERROR IS IN THE VARIABLES NAME "sHoras"
Related
I am trying to extract the numbers from the below page but always showed an exception, I tried various solutions but still get StaleElementReferenceException, here is my code..
I tried sleep and wait...., what is the problem?, please
options = Options()
options.add_argument("start-maximized")
webdriver_service = Service('C:/Users/Lenovo/PycharmProjects/pythonProject/chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 20)
driver.get("https://ec.europa.eu/ecat/category/en/5/dishwasher-detergents")
products = []
num_pages = 7
step = 0
while (step < num_pages):
try:
time.sleep(2)
elm = wait.until(EC.presence_of_all_elements_located((By.XPATH, "//*[#id='producersTableId']/tbody/tr/td[4]")))
time.sleep(2)
products.extend(elm)
for i in products:
print(i.text) # the exception appreas here
elm = wait.until(EC.presence_of_all_elements_located((By.XPATH, "//*[#id='producersTableId']/tbody/tr/td[4]")))
next_Butt = wait.until(EC.element_to_be_clickable((By.XPATH, "//*[#id='producersTableId_next']/a")))
driver.execute_script("arguments[0].click();", next_Butt)
time.sleep(2)
step += 1
except exceptions.StaleElementReferenceException as e :
print(e)
pass
print(len(products))
I've been trying to flag/report a list of spam comments in a particular YouTube video.
For that I've been using this code on Python, which loads my previous profile so I log in with my account:
URL = "https://www.youtube.com/watch?
v=dvecqwfU6xw&lc=Ugxw_nsUNUor9AUEBGp4AaABAg.9fDfvkgiqtW9fDkE2r6Blm"
soup = BeautifulSoup(requests.get(URL).content, "html.parser")
options = webdriver.ChromeOptions()
user = pathlib.Path().home()
print(user)
options.add_argument(f"user-data-dir={user}/AppData/Local/Google/Chrome/User Data/")
driver= webdriver.Chrome('chromedriver.exe',chrome_options=options)
driver.get(URL)
wait=WebDriverWait(driver, 100)
comment_box = '//*[#id="comment"]'
reply_box ='//*[#id="replies"]'
while(True):
driver.execute_script("window.scrollBy(0, 200);")
try:
reply_box = driver.find_element(By.XPATH, reply_box)
print(reply_box.text)
break
except:
pass
# resp = driver.request('POST', 'https://www.youtube.com/youtubei/v1/flag/get_form?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8&prettyPrint=false')
# print(resp.text)
button = wait.until(EC.presence_of_element_located((By.XPATH,'//*[#id="button"]')))
driver.execute_script("arguments[0].click();", button)
The problem comes with opening the menu, I believe since you have to hover over the 3 dots menu it would then appear as the clickable menu so I never get to open the actual menu to report/flag the comment.
My mistake was not to take full Xpath path.... It works perfectly like this, THANKS
options = webdriver.ChromeOptions()
user = pathlib.Path().home()
print(user)
options.add_argument(f"user-data-dir={user}/AppData/Local/Google/Chrome/User Data/")
options.add_argument('--headless')
driver= webdriver.Chrome('chromedriver.exe',chrome_options=options)
driver.get(URL)
wait=WebDriverWait(driver, 100)
comment_box = '//*[#id="comment"]'
reply_box ='//*[#id="replies"]'
while(True):
driver.execute_script("window.scrollBy(0, 200);")
try:
reply_box = driver.find_element(By.XPATH, reply_box)
print(reply_box.text)
break
except:
pass
option_button = '/html/body/ytd-app/div[1]/ytd-page-manager/ytd-watch-flexy/div[5]/div[1]/div/div[2]/ytd-comments/ytd-item-section-renderer/div[3]/ytd-comment-thread-renderer[1]/div/ytd-comment-replies-renderer/div[2]/ytd-comment-renderer/div[3]/div[3]/ytd-menu-renderer/yt-icon-button/button'
option_button = wait.until(EC.presence_of_element_located((By.XPATH, option_button)))
driver.execute_script("arguments[0].click();", option_button)
report_button = '/html/body/ytd-app/ytd-popup-container/tp-yt-iron-dropdown/div/ytd-menu-popup-renderer/tp-yt-paper-listbox/ytd-menu-service-item-renderer/tp-yt-paper-item/yt-formatted-string'
report_button = wait.until(EC.presence_of_element_located((By.XPATH,report_button)))
driver.execute_script("arguments[0].click();", report_button)
report_button_spam = '/html/body/ytd-app/ytd-popup-container/tp-yt-paper-dialog/yt-report-form-modal-renderer/tp-yt-paper-dialog-scrollable/div/div/yt-options-renderer/div/tp-yt-paper-radio-group/tp-yt-paper-radio-button[1]/div[1]'
report_button_spam = wait.until(EC.presence_of_element_located((By.XPATH, report_button_spam)))
driver.execute_script("arguments[0].click();", report_button_spam)
report_button_send = '/html/body/ytd-app/ytd-popup-container/tp-yt-paper-dialog/yt-report-form-modal-renderer/div/yt-button-renderer[2]/a/tp-yt-paper-button'
report_button_send = wait.until(EC.presence_of_element_located((By.XPATH, report_button_send)))
driver.execute_script("arguments[0].click();", report_button_send)
popup_button_done = '/html/body/ytd-app/ytd-popup-container/tp-yt-paper-dialog[2]/yt-confirm-dialog-renderer/div[2]/div[2]/yt-button-renderer[3]/a/tp-yt-paper-button'
popup_button_done = wait.until(EC.presence_of_element_located((By.XPATH, popup_button_done)))
print(popup_button_done.text)
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
Path = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(Path)
driver.get("https://www.emag.ro/")
search_bar = driver.find_element_by_id("searchboxTrigger")
search_bar.send_keys("laptopuri")
search_bar.send_keys(Keys.RETURN)
main = None
try:
main = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "main-container"))
)
print("Page loaded,main retrived succesfully")
except:
driver.quit()
items = main.find_element_by_id("card_grid")
products = items.find_elements_by_css_selector("div.card-item.js-product-data")
count = 0
for product in products:
raw_name = WebDriverWait(product, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "h2.card-body.product-title-zone"))
).text
raw_price = WebDriverWait(product, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, "product-new-price"))
)
#Parsing the product name
raw_name = raw_name.replace("Laptop", "")
raw_name = raw_name.strip()
if raw_name.startswith("Apple"):
sEnd = raw_name.find(",")
else:
sEnd = raw_name.find("cu") - 1
product_name = raw_name[:sEnd]
#Parsing the product price
raw_price = raw_price.text[:raw_price.text.find(" ")]
print(raw_price)
count += 1
print(f"{count} results returned")
driver.quit()
Code works perfectly fine sometimes,but sometimes i get the error:
Please note i am new at this,so an explanation would be very appreciated.I just learned how to use selenium and the reason i transitioned from beautifulsoup because of the lack of wait possibility,and now when trying to use that,i get this error SOMETIMES
See this :
driver = webdriver.Chrome(Path)
and how have you used it here :
try:
main = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "main-container"))
)
print("Page loaded,main retrived succesfully")
If you pay attention you would see that, you are using WebDriverWait(driver, 10) and passing driver reference.
But here
raw_name = WebDriverWait(product, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "h2.card-body.product-title-zone"))
).text
you are passing product in WebDriverWait, which is wrong, you should pass driver reference here. like
raw_name = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "h2.card-body.product-title-zone"))
).text
This should help you past this issue for sure.
also, make changes here
raw_price = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, "product-new-price"))
)
This is what we have internally :
class WebDriverWait(object):
def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):
"""Constructor, takes a WebDriver instance and timeout in seconds.
Update 1 :
driver = webdriver.Chrome(driver_path)
driver.maximize_window()
driver.implicitly_wait(50)
driver.get("https://www.emag.ro/")
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, "//i[contains(#class,'close')]/parent::button[#class='close']"))).click()
ActionChains(driver).move_to_element(wait.until(EC.visibility_of_element_located((By.XPATH, "//button[contains(#class,'js-accept')]")))).click().perform()
search_bar = driver.find_element_by_id("searchboxTrigger")
search_bar.send_keys("laptopuri")
search_bar.send_keys(Keys.RETURN)
main = None
try:
main = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "main-container")))
print("Page loaded,main retrived succesfully")
except:
driver.quit()
items = main.find_element_by_id("card_grid")
products = driver.find_elements_by_css_selector("div.card-item.js-product-data")
count = 0
for product in products:
raw_name = product.find_element_by_css_selector("h2.card-body.product-title-zone a").text
print(raw_name)
raw_price = product.find_element_by_css_selector("p.product-new-price").text
print(raw_price)
#Parsing the product name
# raw_name = raw_name.replace("Laptop", "").strip()
# if raw_name.startswith("Apple"):
# sEnd = raw_name.find(",")
# else:
# sEnd = raw_name.find("cu") - 1
# product_name = raw_name[:sEnd]
#Parsing the product price
# raw_price = raw_price[raw_price.find(" ")]
# print(raw_price)
# count += 1
#print(f"{count} results returned")
driver.quit()
is there a way to get this bot to automaticly restart if the site crashes and is there a way for the bot to refresh the page if the site doesnt load properly. becsause i cant get an xpath on the refresh and i have no clue how to make the bot restart if it didnt accomplish its goals
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
start_time = time.time()
# my code here
path = "C:\Program Files (x86)\Common Files\Chromedriver.exe"
driver = webdriver.Chrome(path)
# open page
driver.get("https://www.usmint.gov/")
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="navigation"]/div[3]/ul/li[2]/a')) #PRODUCT S
)
finally:
# product schedule
driver.find_element_by_xpath('//*[#id="navigation"]/div[3]/ul/li[2]/a').click()
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="navigation"]/div[3]/ul/li[2]/div/div/ul/li[3]/a')) #2020
)
finally:
# 2020 product schedule
driver.find_element_by_xpath('//*[#id="navigation"]/div[3]/ul/li[2]/div/div/ul/li[3]/a').click()
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="4cb2318c15eb72316187ca9691"]/div/div/div[2]/div/div[1]/a')) #birth set
)
finally:
# birth set 2020
driver.find_element_by_xpath('//*[#id="4cb2318c15eb72316187ca9691"]/div/div/div[2]/div/div[1]/a').click()
'''
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="emailmodalclose"]')) #clear
)
finally:
# clear email list stupidity
driver.find_element_by_xpath('//*[#id="emailmodalclose"]').click()
'''
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div[3]/div[2]/div[2]/form/div/div[5]/button[1]')) #add to
)
finally:
# add to bag
driver.find_element_by_xpath("/html/body/div[1]/div[3]/div[2]/div[2]/form/div/div[5]/button[1]").click()# double qoutes?
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="mini-cart"]/div[3]/div[2]/div[3]/a')) #checkout
)
finally:
# checkout
driver.find_element_by_xpath('//*[#id="mini-cart"]/div[3]/div[2]/div[3]/a').click()
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="dwfrm_login_username"]')) #login
)
finally:
# login
driver.find_element_by_xpath('//*[#id="dwfrm_login_username"]').send_keys("email")
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="dwfrm_login_password"]')) #Password
)
finally:
# password
driver.find_element_by_xpath('//*[#id="dwfrm_login_password"]').send_keys("password")
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="checkoutMethodLoginSubmit"]/span')) #checkout as
)
finally:
# checkout as registered user
driver.find_element_by_xpath('//*[#id="checkoutMethodLoginSubmit"]/span').click()
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="dwfrm_billing_paymentMethods_creditCardList"]/option[2]')) #credit card scroll
)
finally:
# credit card scroll
driver.find_element_by_xpath('//*[#id="dwfrm_billing_paymentMethods_creditCardList"]/option[2]').click() # .format?
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="dwfrm_billing_paymentMethods_creditCard_month"]/option[2]')) #cc exp m
)
finally:
# cc exp month
driver.find_element_by_xpath('//*[#id="dwfrm_billing_paymentMethods_creditCard_month"]/option[2]').click()
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="dwfrm_billing_paymentMethods_creditCard_year"]/option[11]')) #cc exp y
)
finally:
# cc exp year
driver.find_element_by_xpath('//*[#id="dwfrm_billing_paymentMethods_creditCard_year"]/option[11]').click()
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="dwfrm_billing_paymentMethods_creditCard_cvn"]')) #cvv
)
finally:
# cvv
driver.find_element_by_xpath('//*[#id="dwfrm_billing_paymentMethods_creditCard_cvn"]').send_keys("999")
time.sleep(2)
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="checkoutContinuePaymentDelegator"]')) #continue to final
)
finally:
# continue to final review
driver.find_element_by_xpath('//*[#id="checkoutContinuePaymentDelegator"]').click()
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="formAgreementLabel"]/span')) #terms of use
)
finally:
# terms of use button
driver.find_element_by_xpath('//*[#id="formAgreementLabel"]/span').click()
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="submitOrderButton"]')) #Place order
)
finally:
# place order
driver.find_element_by_xpath('//*[#id="submitOrderButton"]').click()
print ("time elapsed: {:.2f}s".format(time.time() - start_time))
driver.quit()
#if __name__ == '__main__':
# order(keys)
and if you see anything in the code that can be fixed it would be appreciated
As requested in the comment, this is the simplest but not the ideal way. Since your try except clause does not include an except clause, they serve no purpose in your code except it just suppress all your TimeoutException, which you actually want them as you need to know what error it encounters. To improve this solution, you can consider to split the try except clause and re-execute those wait element lines only instead of the whole script.
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
start_time = time.time()
# my code here
path = "C:\Program Files (x86)\Common Files\Chromedriver.exe"
driver = webdriver.Chrome(path)
while True:
try:
# open page
driver.get("https://www.usmint.gov/")
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="navigation"]/div[3]/ul/li[2]/a')) #PRODUCT S
)
# product schedule
driver.find_element_by_xpath('//*[#id="navigation"]/div[3]/ul/li[2]/a').click()
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="navigation"]/div[3]/ul/li[2]/div/div/ul/li[3]/a')) #2020
)
# 2020 product schedule
driver.find_element_by_xpath('//*[#id="navigation"]/div[3]/ul/li[2]/div/div/ul/li[3]/a').click()
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="4cb2318c15eb72316187ca9691"]/div/div/div[2]/div/div[1]/a')) #birth set
)
# birth set 2020
driver.find_element_by_xpath('//*[#id="4cb2318c15eb72316187ca9691"]/div/div/div[2]/div/div[1]/a').click()
'''
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="emailmodalclose"]')) #clear
)
# clear email list stupidity
driver.find_element_by_xpath('//*[#id="emailmodalclose"]').click()
'''
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div[3]/div[2]/div[2]/form/div/div[5]/button[1]')) #add to
)
# add to bag
driver.find_element_by_xpath("/html/body/div[1]/div[3]/div[2]/div[2]/form/div/div[5]/button[1]").click()# double qoutes?
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="mini-cart"]/div[3]/div[2]/div[3]/a')) #checkout
)
# checkout
driver.find_element_by_xpath('//*[#id="mini-cart"]/div[3]/div[2]/div[3]/a').click()
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="dwfrm_login_username"]')) #login
)
# login
driver.find_element_by_xpath('//*[#id="dwfrm_login_username"]').send_keys("email")
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="dwfrm_login_password"]')) #Password
)
# password
driver.find_element_by_xpath('//*[#id="dwfrm_login_password"]').send_keys("password")
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="checkoutMethodLoginSubmit"]/span')) #checkout as
)
# checkout as registered user
driver.find_element_by_xpath('//*[#id="checkoutMethodLoginSubmit"]/span').click()
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="dwfrm_billing_paymentMethods_creditCardList"]/option[2]')) #credit card scroll
)
# credit card scroll
driver.find_element_by_xpath('//*[#id="dwfrm_billing_paymentMethods_creditCardList"]/option[2]').click() # .format?
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="dwfrm_billing_paymentMethods_creditCard_month"]/option[2]')) #cc exp m
)
# cc exp month
driver.find_element_by_xpath('//*[#id="dwfrm_billing_paymentMethods_creditCard_month"]/option[2]').click()
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="dwfrm_billing_paymentMethods_creditCard_year"]/option[11]')) #cc exp y
)
# cc exp year
driver.find_element_by_xpath('//*[#id="dwfrm_billing_paymentMethods_creditCard_year"]/option[11]').click()
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="dwfrm_billing_paymentMethods_creditCard_cvn"]')) #cvv
)
# cvv
driver.find_element_by_xpath('//*[#id="dwfrm_billing_paymentMethods_creditCard_cvn"]').send_keys("999")
time.sleep(2)
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="checkoutContinuePaymentDelegator"]')) #continue to final
)
# continue to final review
driver.find_element_by_xpath('//*[#id="checkoutContinuePaymentDelegator"]').click()
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="formAgreementLabel"]/span')) #terms of use
)
# terms of use button
driver.find_element_by_xpath('//*[#id="formAgreementLabel"]/span').click()
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[#id="submitOrderButton"]')) #Place order
)
# place order
driver.find_element_by_xpath('//*[#id="submitOrderButton"]').click()
print ("time elapsed: {:.2f}s".format(time.time() - start_time))
driver.quit()
break
except Exception as err:
print(f"Error: {str(err)}, trying again")
pass
#if __name__ == '__main__':
# order(keys)
Can't Click on the button 'consultar' and select the line I want
import time
import xlrd # importando a biblioteca
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
import zipfile
inicio = time.time()
# datapagamento = time.strftime(input('Qual a data de pagamento?'))
# data = time.strftime(input('Qual o mês de referência?'))
datainicial = "042019"
# Pegando nome do mês para salvar
if datainicial.startswith('01'):
mes = 'Janeiro'
elif datainicial.startswith('02'):
mes = 'Fevereiro'
elif datainicial.startswith('03'):
mes = 'Março'
elif datainicial.startswith('04'):
mes = 'Abril'
elif datainicial.startswith('05'):
mes = 'Maio'
elif datainicial.startswith('06'):
mes = 'Junho'
elif datainicial.startswith('07'):
mes = 'Julho'
elif datainicial.startswith('08'):
mes = 'Agosto'
elif datainicial.startswith('09'):
mes = 'Setembro'
elif datainicial.startswith('10'):
mes = 'Outubro'
elif datainicial.startswith('11'):
mes = 'Novembro'
elif datainicial.startswith('12'):
mes = 'Dezembro'
else:
print('Insira data iniciando do dia 01')
workbook = xlrd.open_workbook('teste.xlsx') # Escolhe o arquivo a ser lido.
worksheet = workbook.sheet_by_index(1) # Escolha a aba a ser lida.
# Pega as informações do Excel
i = 0
while (i in range(worksheet.nrows)):
#cnpj = worksheet.cell_value(rowx=i, colx=0)
#senha = worksheet.cell_value(rowx=i, colx=1)
#empresa = worksheet.cell_value(rowx=i, colx=2)
cnpj = '13177807000146'
senha = 'qualita#2018'
i = i + 1
driver = webdriver.Chrome()
# driver.maximize_window()
driver.get("https://directa.natal.rn.gov.br/")
# Logando
driver.switch_to.frame(driver.find_element_by_name("mainsystem"))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "usuario"))).send_keys(cnpj)
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "senha"))).send_keys(str(senha))
time.sleep(2)
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "button.btn#acessar"))).click()
# Nota natalense
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME, "mainsystem")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, 'limenu9'))).click()
time.sleep(1)
# operações
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "#limenu9 > div > a:nth-child(3) > span:nth-child(1)")))
element = driver.find_element(By.CSS_SELECTOR, '#limenu9 > div > a:nth-child(3) > span:nth-child(1)')
webdriver.ActionChains(driver).move_to_element(element).perform()
# Emissão de DAM
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[#id="formsmenu14"]/li[5]/a'))).click()
# Trocando frame
time.sleep(1)
driver.switch_to.frame(0)
driver.switch_to.frame(0)
# Selecionando empresa
WebDriverWait(driver, 10).until(EC.element_to_be_clickable( (By.XPATH, '/html/body/form/div/div[2]/div[2]/div[10]/div[2]/div/div/table/tbody/tr/td'))).click()
WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, '/html/body/div[4]/table/tbody/tr[2]/td/select/option[2]'))).click()
# Consultar
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[#id="lay"]/div[2]/div[2]/div[6]/div/table/tbody/tr'))).click()
# selecionando o mês do DAM
driver.find_elements_by_xpath('//div[contains(text(), "{}") and #class="inner"]'.format(datainicial)).doubleClick()
fim = time.time()
duracao = fim - inicio
print('O programa rodou em: {} e foram baixadas {} empresas'.format(duracao, i))
Your /html/body/form/div/div[2]/div[2]/div[10]/div[2]/div/div/table/tbody/tr/td XPath expression is not the best option of identifying web elements, if you want to click the link with Consultar text it's better to amend your selector to look like:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, 'Consultar')))
if you still want to use XPath - you can use text() function like:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[text()='Consultar']")))
Sometimes DOM elements cannot be clickable by Selenium's click() function, in this case you can work it around by executing a JavaScript call like:
driver.execute_script("arguments[0].click()", driver.find_element_by_link_text("Consultar"))