python - 单击 Selenium 容器中的每个 div

标签 python selenium

我正在使用 selenium 自动访问 https://www.nemlig.com/的页面,但我不知道如何迭代(比方说)8 个 div,所有内容都包含在另一个 div 中。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
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(executable_path = r'C:\Users\user\lib\chromedriver_77.0.3865.40.exe')
wait = WebDriverWait(driver,10)
driver.maximize_window()
driver.get("https://www.nemlig.com/")

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".timeslot-prompt.initial-animation-done")))
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[type='tel'][class^='pro']"))).send_keys('2300')
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".btn.prompt__button"))).click()

以上是到目前为止的代码。完成此操作后,我想以给定的时间间隔一一访问日期按钮。

enter image description here

我在实现这一点时遇到了问题,因为它们在 HTML 中看起来都一样。我如何告诉网络驱动程序单击容器内的下一个 div,直到所有 8 个日期都已访问为止?

最佳答案

引入 WebDriverWaitpresence_of_all_elements_ located() 以及以下 CSS 选择器。我添加了日期检查,以检查列表中是否存在可用日期,然后单击该日期。

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
import time

driver = webdriver.Chrome(executable_path = r'C:\Users\user\lib\chromedriver_77.0.3865.40.exe')
wait = WebDriverWait(driver,20)
driver.maximize_window()
driver.get("https://www.nemlig.com/")

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".timeslot-prompt.initial-animation-done")))
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[type='tel'][class^='pro']"))).send_keys('2300')
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".btn.prompt__button"))).click()
dates=[]
elements=wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,"div[data-automation='dayDateTmSlt']")))
for ele in elements:
    if ele.text not in dates:
       dates.append(ele.text)
       driver.execute_script("arguments[0].click();", ele)
       time.sleep(3)

关于python - 单击 Selenium 容器中的每个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58376548/

相关文章:

ruby-on-rails - Cucumber + webrat + selenium,如何忽略隐藏文本?

python - 覆盖范围未显示 virtualenv 中执行的行

python - 如何在 for 循环中使用多重处理?如何让一个核心运行从索引n1到n2的循环,另一个核心从索引n2到n3运行循环?

python - 为什么 lxml 找不到 Chrome 检查器给出的 xpath?

python - 更新 Django - 错误 : 'No module named migration'

java - 如果 3 个按钮相同,如何使用 selenium 代码选择第二个按钮

python - 在 Internet Explorer (Python) 中使用 Selenium 绕过 SSL 认证

python - 如何在 Python 中使用 Selenium 提取文本元素?

javascript - 在 Selenium WebDriver 中使用 execute_async_script

c# - 抓取基于登录的网站的最佳方式是什么?