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

2024-06-02 06:19:18 发布

您现在位置:Python中文网/ 问答频道 /正文

该公司有一个100多个站点的列表,我正试图使用SeleniumWebDriver自动将用户带入该站点。我对编程相当陌生,所以如果我的问题措辞不当,请原谅我。。但是,我试图从用户那里获取一个站点的名称,例如下面示例中的“Alpharetta-Cemex”,并在这个长列表中找到它,然后选择该链接。通过测试,我非常确定我需要点击的元素是h3类,该类也包含数据hmi名称下的站点名称

网站代码示例: enter image description here

我试着使用下面的方法,但似乎从来都不起作用

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编程新手,如果你能解释我做错了什么,我将永远感激你


1条回答
网友
1楼 · 发布于 2024-06-02 06:19:18

如果要单击单个链接(例如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

如果上述情况不起作用。如果您的链接不在屏幕中/不可见。您可以使用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

相关问题 更多 >