【问题标题】:Selenium web driver code in python for clicking an imagepython中用于单击图像的Selenium Web驱动程序代码
【发布时间】:2018-05-03 11:46:26
【问题描述】:

我需要 Python 代码方面的帮助,以便我可以使用 selenium webdriver 将图像上的点击事件设置为 Sony。 我是 selenium 网络驱动程序和 python 的新手。 请注意,点击“Testing Inc.”后图片,将显示下一页有登录详细信息。

这里是 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:\SCripts\IEDriverServer.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();

【问题讨论】:

  • 分享相关的 HTML。

标签: python-3.x selenium selenium-webdriver webdriver webdriverwait


【解决方案1】:

当您使用 by_partial_link_text 进行搜索时,Selenium 需要在 a html 标记内的文本。因为它在span 里面,所以它不会找到它。

你可以做什么:

  1. 编写一个 Css 选择器以仅使用标签和属性来查找包含所需图像的标签。在这里,您需要检查整个 HTML。由于我无权访问,我只能假设以下示例。

    div.idpDescription span
    
  2. 根据文本内容编写 XPath。 XPath 可能对您来说更难理解,因为您不习惯使用 Selenium 进行开发。

    //span[text()='Sony Inc.']
    

【讨论】:

    【解决方案2】:

    根据您共享的 HTML 和代码试用,因为您尝试在 WebElement 上调用 click(),文本为 Sony Inc. 您需要诱导 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()
    

    【讨论】:

    • 非常感谢 Debanjan,您解决了我的问题。感谢您分享详细信息。
    猜你喜欢
    • 2016-09-29
    • 2018-01-22
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多