为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

子衿沉夜 2023-06-27 16:19:00
该公司有 100 多个网站的列表,我正在尝试使用 Selenium webdriver 自动将用户带入该网站。我对编程相当陌生,所以如果我的问题措辞不好,请原谅我。但是,我试图从用户那里获取一个网站的名称,例如下面示例中的“Alpharetta - Cemex”,并在这么长的内容中找到它列表,然后选择该链接。通过测试,我非常确定我需要单击的元素是h3 类,该类还保存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 existfor card in theCards:    #title = card.find_elements_by_tag_name("h3")    print(card.text)    if(card.text == theSite):        card.click()任何帮助或指导将不胜感激!我是 Python 编程新手,如果你能解释我做错了什么,我将永远感激不已!
查看完整描述

1 回答

?
慕姐8265434

TA贡献1813条经验 获得超2个赞

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


查看完整回答
反对 回复 2023-06-27
  • 1 回答
  • 0 关注
  • 124 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信