【问题标题】:How can make (style ="display: none;") element visible in HTML in python selenium?如何在 python selenium 中使 (style ="display: none;") 元素在 HTML 中可见?
【发布时间】:2018-03-15 18:45:26
【问题描述】:

我正在尝试在一个网站上使用 python selenium 上传文件,其 html 中的文件字段如下所示:

 <div id="fallback" style="display: none;">
    <input id="upload-input" type="file" name="file" multiple="multiple">
    <div id="upload-progress" class="upload-progress"></div>
  </div>

我正在尝试通过以下代码使元素可见:

elem = driver.find_element_by_xpath("//input[@id='upload-input']")
driver.execute_script("arguments[0].removeAttribute('style')", elem)
elem = driver.find_element_by_xpath("//input[@id='upload-input']")

运行脚本后,脚本停止,不上传文件,也不抛出任何错误。

使用elem.is_displayed()后,我发现即使运行了上面的代码块,元素仍然没有显示。

【问题讨论】:

标签: python html selenium


【解决方案1】:

style 属性位于包装 &lt;div&gt; 上,但您正试图将其从 &lt;input&gt; 中删除:

container = driver.find_element_by_id("fallback")
driver.execute_script("arguments[0].style.display = 'block';", container)

input = driver.find_element_by_id("upload-input")
input.send_keys(path_to_file)

P.S. style 属性的使用是如何元素样式的实现细节。在这种情况下,您实际上只关心 样式是什么,因此最好将其具体设置 为您想要的,而不是 删除 特定的实现它的方式。前者应该不那么脆。

P.P.S. 您可能不需要将 XPath 用于像通过 ID 查找这样简单的事情。 (ID 在所有元素中应该是唯一的;否则它们就不是真正的 ID。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    相关资源
    最近更新 更多