html 为什么Selenium在这个函数中不接受动态变量?

pb3skfrl  于 2022-12-16  发布在  其他
关注(0)|答案(2)|浏览(101)

为什么会这样:

monday_div = driver.find_element(By.XPATH, '//*[@id="GXPMonday"]')

但这个不是吗

weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

for day in weekdays:
    main_day_div = driver.find_elements(By.XPATH, '//*[@id="GXP' + day + '"]')

我收到以下错误

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="GXPMonday"]

这是我试图解析的网站:https://movatiathletic.com/clubs/schedule.php?acct=663&loc=2860

jljoyd4f

jljoyd4f1#

试试这个...

main_day_div = driver.find_element(By.ID,f"GXP{day}")

如果这不起作用,您可能遇到了时间问题,此时使用expected_conditions会更好。

from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait

wait = WebDriverWait(driver, timeout=30)
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

for day in weekdays:
    main_day_div = wait.until(ec.presence_of_element_located((By.ID,f"GXP{day}")))
hl0ma9xz

hl0ma9xz2#

您的定位器是正确的,您需要添加一些等待时间,只是添加了打印GXPTitle的代码供您参考,请检查:

weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    
for day in weekdays:
    main_day_div = WebDriverWait(driver, 15).until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="GXP' + day + '"]//h6')))
    print("Total titles in -", day ,":", len(main_day_div))
    print("-------")
    for title in main_day_div:
        print(title.text)
    print("=======")

相关问题