尽管添加了 time.sleep(),Selenium 仍无法定位元素

时间:2021-04-30 13:37:00

标签: python html python-3.x selenium web-scraping

我编写了一个脚本来查找并单击一个按钮,直到今天它都运行良好。我想知道是什么原因造成的:

item

我尝试添加 time.sleep() 只是为了确保我等待页面加载时间足够长,但没有,错误仍然出现。这是按钮的html:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"button[data-bind="click:selectLocation"]"}

这是查找并单击按钮的代码片段:

<div class="form-group">                    
 <div class="col-xs-12">                       
   <label data-bind="lang:searchSelectLocation">Select a location</label>                        
  <button type="button" class="btn btn-default btn-block text-left" data-bind="click:selectLocation">                            <i class="fa fa-fw fa-map-marker-alt" data-bind="css:loadingLocation ? 'fa-spinner fa-spin' : 'fa-map-marker-alt'"></i>&nbsp;<!--ko text: location ? location.name : $root.lang('searchSelectLocationOptions') -->Cityname<!--/ko--><i class="fa fa-chevron-right pull-right"></i>                        
  </button>                  
 </div>               
</div>

P.S 我也已经在点击之前等待了。很抱歉错过了。

1 个答案:

答案 0 :(得分:0)

嗯,首先你应该在点击按钮之前等待,而不是之后,以确保它被加载。

其次,Selenium 带有所谓的 Explicit Waits,允许您等待元素可见或可点击。

所以在你的情况下,这看起来像这样:

max_time_to_wait = 200 # if it doesn't find the element in this timespan, it will throw a TimeoutException
element = WebDriverWait(driver, max_time_to_wait).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, 'button[data-bind="click:selectLocation"]')))
element.click()
相关问题