Dan*_*ney 2 python selenium selenium-webdriver webdriverwait expected-condition
我正在构建一个网络抓取工具,它循环访问地址列表并在房地产网站上搜索它们。然后,它会根据我们已经了解的有关房产的信息更新一些下拉列表,然后再抓取各种信息,例如预期租金收益率。
搜索完每个地址后,可能需要一些时间才能将所需元素(例如“bathrooms_dropdown”)加载到网站上。我一直在使用它来管理它,time.sleep(x)但这很慢且不可靠,并且implictly_wait(60)似乎没有任何效果,因为我仍然经常收到“元素不存在/无法找到”错误。
我确信我需要实现 WebDriverWait,但在将其实现到我的代码中时无法计算出语法。我还没有看到任何与此结合使用的例子driver.find_elements()
任何帮助将不胜感激!
driver.get(url)
driver.implicitly_wait(60)
# find search bar and search for address
searchBar = driver.find_element(by = By.ID, value = 'react-select-3-input')
searchBar.send_keys(address)
searchButton = driver.find_element(By.CLASS_NAME, value='sc-1mx0n6y-0').click()
# wait for elements to load
time.sleep(3) # REPLACE THIS
# find dropdown and click to open it
bathrooms_dropdown = driver.find_elements(By.CLASS_NAME, value = 'css-19bqh2r')[-2]
bathrooms_dropdown.click()
Run Code Online (Sandbox Code Playgroud)
您需要注意以下几件事:
由于searchBar元素是一个可点击元素,理想情况下您需要为element_to_be_clickable()引入WebDriverWait,如下所示:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "react-select-3-input"))).send_keys(address)
Run Code Online (Sandbox Code Playgroud)
同样,由于searchButton元素是可点击元素,因此您需要为element_to_be_clickable()引入WebDriverWait,如下所示(在最坏的情况下,假设填充搜索文本时启用 searchButton):
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CLASS_NAME, "sc-1mx0n6y-0"))).click()
Run Code Online (Sandbox Code Playgroud)
理想的下拉菜单是html-select标签,理想情况下您应该使用Select类引发WebDriverWait,如下所示:
Select(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "cssSelector_select_element")))).select_by_visible_text("visible_text")
Run Code Online (Sandbox Code Playgroud)
最后,您使用的ID和值例如react-select-3-input、sc-1mx0n6y-0、css-19bqh2r等看起来是动态的,并且当您重新访问应用程序或在短时间内访问应用程序时可能会发生变化。因此,您可能会选择寻找其他一些静态属性。CLASS_NAME
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6516 次 |
| 最近记录: |