我需要python代码的帮助,以便我可以使用selenium
webdriver
在图像上单击事件作为Sony
。 我是Selenium Web Driver和python的新手。 请注意,单击"测试公司"图像后,将显示下一页具有登录详细信息。
这是Javascript代码:-
<div class="idpDescription float"><span class="largeTextNoWrap indentNonCollapsible">Sony Inc.</span></div> <span class="largeTextNoWrap indentNonCollapsible">Sony Inc.</span>
我编写的 Python 代码,但单击图像时未发生单击事件:-
import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
# get the path of IEDriverServer
dir = os.path.dirname(file)
Ie_driver_path = dir + "IEDriverServer.exe"
#create a new IE session
driver = webdriver.Ie("D:SCriptsIEDriverServer.exe")
driver.maximize_window()
#navigate to the application home page
driver.get("example.com")
element=driver.find_element_by_partial_link_text("Testing Inc.").click();
当你使用by_partial_link_text
进行搜索时,Selenium 需要a
html 标签中的文本。因为它在span
内,所以它不会找到它。
您可以执行的操作:
-
编写 Css 选择器以仅使用标记和属性查找包含所需图像的标记。在这里,您需要检查整个 HTML。由于我无法访问它,因此我只能假设以下示例。
div.idpDescription span
-
根据文本内容编写 XPath。XPath 对你来说可能更难理解,因为你不习惯用 Selenium 开发。
//span[text()='Sony Inc.']
根据您共享的HTML和您的代码试用版,当您尝试在WebElement上以索尼公司的身份使用文本调用click()
时,您需要诱导WebDriverWait元素可点击,如下所示:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# other lines of code
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='idpDescription float']/span[@class='largeTextNoWrap indentNonCollapsible']"))).click()
您可以更精细地将链接文本添加到xpath,如下所示:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# other lines of code
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='idpDescription float']/span[@class='largeTextNoWrap indentNonCollapsible' and contains(.,'Sony Inc.')]"))).click()