selenium.common.exceptions.NoSuchElementException在python 3.7中使用硒

时间:2019-06-19 08:21:45

标签: selenium xpath python-3.7

我正在尝试使用硒来自动化从打开特定网站登录到搜索特定文章的过程。我可以执行的步骤很少,但是在“登录”步骤中遇到错误。

from selenium import webdriver
from selenium.webdriver.common.by import By
base = 'https://www.wsj.com'
url = 'https://www.wsj.com/search/term.html?KEYWORDS=cybersecurity&min-date=2018/04/01&max-date=2019/03/31&isAdvanced=true&daysback=90d&andor=AND&sort=date-desc&source=wsjarticle,wsjpro&page=1'

browser = webdriver.Safari(executable_path='/usr/bin/safaridriver')
browser.get(url)
browser.find_element_by_id('editions-select').click()
browser.find_element_by_id('na,us').click()
browser.find_element(By.XPATH,"//button[@type='button' and contains(.,'Sign In')]").click()
browser.find_element_by_id('username').send_keys('**#&^&@$@#$')
browser.find_element_by_id('password').send_keys('@#@$%%**')
browser.find_element_by_id('basic-login').click()
browser.find_element_by_id('masthead-container').click()
browser.find_element_by_id('searchInput').send_keys('cybersecurity')
browser.find_element_by_name('ADVANCED SEARCH').click()
browser.find_element_by_id('dp1560924131783').send_keys('2018/04/01')
browser.find_element_by_id('dp1560924131784').send_keys('2019/03/31')
browser.find_element_by_id('wsjblogs').click()
browser.find_element_by_id('wsjvideo').click()
browser.find_element_by_id('interactivemedia').click()
browser.find_element_by_id('sitesearch').click()

代码将一直运行到此行:     browser.find_element_by_id('na,us')。click()

但是在那之后它显示错误:     browser.find_element(By.XPATH,“ // button [@ type ='button'并且包含(。,'Sign In'']]”))。click()

错误消息显示: selenium.common.exceptions.NoSuchElementException

我应该怎么做才能使其正常工作?有什么问题吗?

1 个答案:

答案 0 :(得分:2)

您应该使用WebDriverWait

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import WebDriverWait

botton_to_click = WebDriverWait(driver, 10).until(EC.element_to_be_clickable, ((By.XPATH,"//button[@type='button' and contains(.,'Sign In')]")))
botton_to_click.click()

希望这对您有帮助!