[Environment]: Python + Selenium
我正在尝试将本地文件上传到上传文件按钮。
首先,我尝试查看是否可以找到该元素并单击该按钮,然后使用
driver.switch_to_frame("upload_frame")
driver.find_elements(By.ID, 'id_file').click()
因此,我使用了相同的方法,但将click()
替换为文件上传的send_keys()
。
driver.switch_to_frame("upload_frame")
driver.find_elements(By.ID, 'id_file').send_keys("xxx.bin")
但它不能传递值。
因此,我尝试使用其他定位器,如下所示:(它们都不起作用)
driver.find_element(By.XPATH, "//button[text()='Update from File']")
driver.find_elements(By.XPATH, "//*[@id='id_file']")
driver.find_elements(By.XPATH, "//input[@id='file']")
此外,我还用谷歌搜索了很多类似的问题,但找不到解决方案/答案。
想征求您的意见并告诉我一些信息吗?谢谢。
HTML代码片段:
<iframe id="upload_frame" height="30px" frameborder="0" width="0" src="/web/setting/upload.html?r=1422498136526" scrolling="no"
name="upload_frame" style="width: 170px;">
<!DOCTYPE html>
<html>
<head>
<body onload="page_load();">
<div id="content" class="b1">
<form id="form_firm" action="/cgi-bin/system_mgr.cgi" enctype="multipart/form-data" method="post" name="form_firm">
<input type="hidden" value="cgi_firmware_upload" name="cmd">
<div class="file_input_div">
<button id="id_file" type="button" style="border: 2px solid rgb(70, 70, 70); background: none repeat scroll 0% 0% rgb(33, 33, 33);">
<span class="_text" lang="_firmware" datafld="update_b">Update from File</span>
</button>
<input id="file" class="file_input_hidden" type="file" onchange="start_upload();" onclick="clear_upload_path();" style="cursor:pointer"
name="file">
</div>
</form>
</div>
</body>
</html>
</iframe>
driver.find_elements(By.ID, 'id_file').send_keys("xxx.bin")
不起作用,因为它对应于button element
而不是带有类型文件的input element
。
对于使用 selenium 的简单文件上传,您必须首先搜索类型为 file 的输入标签。与您的代码一样,这必须是:
<input id="file" class="file_input_hidden" type="file" onchange="start_upload();" onclick="clear_upload_path();" style="cursor:pointer" name="file">
请使用以下代码使文件上传正常工作:
driver.switch_to_frame("upload_frame")
driver.find_element(By.ID, 'file').send_keys('//path of the file to upload')
注意:- 以上对应于"带有文件类型的输入标签"。