Selenium / Python:找到正确位置后从长列表中选择一个link

Selenium / Python: Selecting a link from a long list after finding the correct location

该公司有 100 多个站点的列表,我正在尝试使用 Selenium webdriver 自动将用户带到该站点。我对编程还很陌生,所以如果我的问题措辞不当,请原谅我。但是,我正在尝试使用示例中的网站名称,例如“Alpharetta - Cemex”从用户下面找到它,然后在这个长列表中找到它,然后 select 那 link。通过测试,我很确定我需要单击的元素是 h3 class,它也包含 data-hmi-name 下的站点名称

网站代码示例:

我试过使用下面的方法,但似乎从来没有用过..

driver.find_element_by_css_selector("h3.tru-card-head-text uk-text-center[data-hmi-name='Alpharetta - Cemex']").click()
 
#For this one I tried to select the h3 class by searching for all those elements that has the name Alpharetta - Cemex

**theCards = main.find_elements_by_tag_name("h3")** #I tried both of these declarations for theCards
**#theCards = main.find_elements_by_class_name("tru-card-wrapper")**

#then used the loop below. This obviously didn't work and it just returns an error that card.text doesn't actually exist

for card in theCards:
    #title = card.find_elements_by_tag_name("h3")
    print(card.text)
    if(card.text == theSite):
        card.click()

如有任何帮助或指导,我们将不胜感激!我是 Python 的编程新手,如果您能解释我做错了什么,我将永远感激不已!

如果您想点击单个 link(例如 Alpharetta - Cemex),您可以尝试如下操作:

theSite = "Alpharetta - Cemex" #You can store user inputted site Name here
linkXpath = "//a[h3[contains(text(),'"+theSite +"']]"
    
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, linkXpath))).click() #This will wait for element to be clickable before it clicks

以防上述情况无效。如果您的 Link 不在屏幕上/不可见。您可以使用 java 脚本首先滚动到元素并单击 ,如下所示:

ele = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, linkXpath)))
driver.execute_script("arguments[0].scrollIntoView();", ele )
driver.execute_script("arguments[0].click();", ele )

您需要导入:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait