使用Selenium在页面上查找动态命名的元素

时间:2019-07-21 01:47:53

标签: python selenium selenium-webdriver selenium-chromedriver

我正在尝试使用Selenium查找并单击网页的一部分,以便添加评论。不过,我在弄清楚如何做到这一点时遇到了麻烦。

元素的class似乎在页面之间变化。文档中有多个相似的元素也无济于事。到目前为止,这是我提出的内容:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=/Users/me/Library/Application/Support/Google/Chrome/Default")
chrome_options.add_argument('--profile-directory=Profile 1')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("https://link-i-want-to-visit")
comment_section = driver.find_elements_by_xpath(("//input"))
print comment_section
comment_section.click()

以下是相关页面中的一些标记:

<input class="sc-iKpIOp igoGaM" placeholder="Add a comment…">

在此站点上的每个不同的URL上,类名似乎已更改。我该如何规避该限制,单击进入输入字段并发送我的评论?

任何指导将不胜感激。如果有帮助,此输入字段似乎会是页面上的最后一个,但我不知道这是否有意义(看来)。

2 个答案:

答案 0 :(得分:1)

您不能使用不包含类的绝对xpath吗?

例如/ html / body / div / div / div / div / div / div / div / div / div / div / p / p [1]是您在此页面上的“我正在尝试...”段落。

也可以尝试// // input [placeholder =“添加评论...”]

答案 1 :(得分:0)

comment_section = driver.find_elements_by_xpath("//input")

这将返回列表。因此您无法单击列表。您应该使用driver.find_element_by_xpath("//input")单击元素。

但是,为了获得最佳实践,请使用WebDriverWait并等待元素element_to_be_clickable 然后单击。

comment_section=WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.XPATH,"//input[@placeholder='Add a comment…']")))
comment_section.click()

OR

comment_section=WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.XPATH,"//input[contains(@placeholder,'Add a comment')]")))
comment_section.click()

您需要使用以下导入来执行以上代码。

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