SO 上有很多关于如何在 Selenium 中使用文件选择器的帖子,但它们似乎都认为您有一个代表文件选择器对话框的元素的引用,通常是因为您知道该元素的 ID。你怎么找到这个?我使用“检查元素”的常规方法不起作用,因为无法在打开文件选择器对话框的情况下打开“检查元素”。
有问题的页面是 images.bing.com。当您点击相机(“使用图像搜索”)然后点击浏览时,文件选择器出现。
这是我尝试过的。我编写此函数是为了获取所有可见元素的列表,这样我就可以在单击链接以显示文件选择器之后而不是之前查看哪些元素是可见的。此过程标识了三个这样的元素,但当我运行 elem.get_attribute("id") 或 elem.get_property("id") 时,它们都没有 ID。
def get_visible_elements(self):
result = set()
for elem in self.driver.find_elements_by_css_selector("*"):
try:
if elem.is_displayed():
result.add(elem)
except StaleElementReferenceException:
pass
return result
请您参考如下方法:
按照给出的步骤 in this Selenium tutorial , 要上传文件,您不是在寻找对话框元素本身,而是在寻找 <input type="file">生成它的 HTML 元素。
要找到它,通常您可以检查调出文件选择对话框的按钮。如果没有,检查它附近的东西并查看附近的 HTML。
在这种情况下,对于 images.bing.com,我检查了显示 "Drag an image here or browse" 的按钮,在附近我找到了应该起作用的元素:
<input id="sb_fileinput" class="fileinput" type="file" accept="image/gif, image/jpeg, image/png, image/webp">
