有以下页面。
您需要在上面选择特定的country
和click
,但是在计算下一行时,出现错误。
引发TimeoutException(消息,屏幕,堆栈跟踪) selenium.common.exceptions.TimeoutException
select = driver.find_element_by_class_name('f1wrnyr7')
select.click()
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[contains(@class, 'md_countryName_fdxiah8') and text()='Colombia']")))
element.click()
答案 0 :(得分:2)
为获得最佳效果,您必须滚动到页面底部,然后单击选择国家/地区,然后单击您要的国家/地区,尝试以下操作:
#scroll to bottom page
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
#wait and click country selection, update locator
elmt = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[@class='selectButton_f1lu1q03']")))
elmt.click()
#wait and click you country want
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[contains(@class, 'md_countryName_fdxiah8') and text()='Colombia']")))
element.click()
答案 1 :(得分:1)
引发异常是因为您的代码能够在DOM中找到元素,但是该元素在页面上不可见。此外,div
的父span
包含一个名为hidden
的属性。以下是DOM结构
<div hidden="">
<div class="f1g5w0oh">
<div class="rm-container">
<div class="rm-row">
<div class="rm-col-sm-12 order-sm-last">
<div class="f1o6pohl">
<h5 class="foyw123">Send Money To</h5>
<div class="rm-row fywghj7">
<div class="rm-col-md-6 rm-col-lg-4 fhdzg5g">
<div class="rm-col-md-6 rm-col-lg-4 fhdzg5g">
<div class="rm-col-md-6 rm-col-lg-4 fhdzg5g">
<div class="rm-col-md-6 rm-col-lg-4 fhdzg5g">
<div class="rm-col-md-6 rm-col-lg-4 fhdzg5g">
<div class="rm-col-md-6 rm-col-lg-4 fhdzg5g">
<div class="rm-col-md-6 rm-col-lg-4 fhdzg5g">
<div>
<a class="f12qs1j9" href="/us/en/colombia">
<span>
<img class="md_flag_ffypto0" src="https://media.remitly.io/COL_32x21@2x-471f08f81b303eb2d3ac61da0909673f.png" alt="Colombia"/>
<span class="md_countryName_fdxiah8">Colombia</span>
</span>
最好的方法是手动重现步骤,并了解使元素可见所需的步骤顺序。
答案 2 :(得分:1)
下面更好地使用定位器。要选择国家(地区)下拉菜单。有时来自国家/地区下拉菜单也可以选择,这就是为什么您可以在下面查找代码以获取最新的下拉列表。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 5)
# get all dropdown elements
select_a_countries = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "img[alt='Open']")))
# filter by visibility
select_a_countries = list(filter(lambda x: x.is_displayed(), select_a_countries))
# we need last one
country_to = select_a_countries[-1]
country_to.click()
# get country we need by alt attribute, should be parameterized
country = driver.find_element_by_css_selector("img[alt='Mexico']")
# scroll to and click
# same as JavaScript: driver.execute_script("arguments[0].scrollIntoView(true);", country)
country.location_once_scrolled_into_view
country.click()