0

I am a newbie to Selenium and HTML. I'm testing a website using Selenium WebDriver, but the driver can't find an element.

My code is:

browser = webdriver.Chrome()
wait = WebDriverWait(browser, 10)
data = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#search_result_former > div.re-content.search-mode-content > div.list-container > ul > li:nth-child(1) > div > div.item-footer > div > a:nth-child(1)')))

The HTML is:

<div class="btn-group clear">
                        <a href="javascript:;" class="btn btn-operation" role="detail">详览</a>
                        <a href="javascript:;" class="btn btn-operation" role="lawState" an="CN201820052763" pn="CN207117855U">法律状态</a>
                        <a href="javascript:;" class="btn btn-operation" role="proposor" _name="信阳农林学院;" _address=" 河南省信阳市羊山新区新24大街信阳农林学院;" _zipcode="464000;" _country="">申请人</a>
                        <a href="javascript:;" role="addAnalysis" class="btn btn-operation">+ 分析库</a>
                        <a href="javascript:;" role="favorite" class="btn btn-operation">收藏</a>
                        <a href="javascript:;" role="translate" _id="CN201820052763.420180316XX" class="btn btn-operation btn-translate">翻译</a>
                        </div>

The result after I run my code:

*raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:* 

Actually, I can see the element. I mean, the element has been loaded. I have tried XPATH, but it doesn't work.

binke ou
  • 15
  • 7

2 Answers2

0

As per the HTML you have shared you can use the following line of code :

  • Through LINK_TEXT :

    wait = WebDriverWait(browser, 10)
    data = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "详览")))
    
  • Through CSS_SELECTOR :

    wait = WebDriverWait(browser, 10)
    data = wait.until(EC.element_to_be_clickable((By.XPATH, "//a[@class='btn btn-operation' and contains(.,'详览')]")))
    
  • Through CSS_SELECTOR :

    wait = WebDriverWait(browser, 10)
    data = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.btn.btn-operation[role='detail']")))
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • I just known why I can't locate the item. Because a new window is opened and I need to switch to the new one. Thanks for ur help! – binke ou Mar 21 '18 at 13:22
0

Use the JavaScript executor to click on an element, because sometime element may be overlayed by another element:

driver = webdriver.Firefox()

driver.get("http://stackoverflow.com/questions/7794087/running-javascript-in-selenium-using-python")
driver.execute_script("document.getElementsByClassName('comment-user')[0].click()") 
Ratmir Asanov
  • 6,237
  • 5
  • 26
  • 40
Vel Guru
  • 394
  • 1
  • 3
  • 16
  • I just known why I can't locate the item. Because a new window is opened and I need to switch to the new one. `windows = browser.window_handle` `browser.switch_to.window(windows[-1])` thanks for ur help! – binke ou Mar 21 '18 at 13:19