[英]Python - Retrieve file for a browser page's <input type=“file”> through a filepath (or any alternative)
I'm trying to automate uploading a file into a browser page through Python in Terminal. 我正在尝试通过Terminal中的Python自动将文件上传到浏览器页面。 The browser page's code has
浏览器页面的代码具有
<input type="file" id="upload_input"/>
which opens an OS level dialog box, where I'm getting stuck. 这会打开一个OS级别对话框,在这里我陷入困境。 Is there a way to somehow override the OS level dialog box that opens by pointing it to a filepath or any alternative using Python?
有没有一种方法可以通过将其指向文件路径或使用Python的任何替代方法来覆盖打开的OS级别对话框? I'm overriding because I've been using Selenium to interact with the browser page and my code gets stuck here, where I have to interact with an OS level dialog box.
我之所以如此,是因为我一直在使用Selenium与浏览器页面进行交互,并且我的代码被卡在这里,在这里我必须与OS级别的对话框进行交互。
Note: the page isn't my page so I can't go in and change the html code. 注意:该页面不是我的页面,因此我无法进入并更改html代码。
Thanks! 谢谢!
Try this: 尝试这个:
driver.find_element_by_id("upload_input").send_keys(r"C:\path_to_file.txt")
driver.find_element_by_id("submit_button").click()
If the test file is located in the same folder as your test script you can use the following: 如果测试文件与测试脚本位于同一文件夹中,则可以使用以下命令:
driver.find_element_by_id('upload_input').send_keys(os.getcwd()+"/testupload.xlsx")
driver.find_element_by_css_selector('input[type="submit"]').click()
In this case, os.getcwd()
locates the 'current working directory' which is where the test script is located. 在这种情况下,
os.getcwd()
找到测试脚本所在的“当前工作目录”。 I add the filename with string concatenation, you can use the same method to add for instance a directory. 我使用字符串连接添加文件名,您可以使用相同的方法来添加目录。 Unlike explicit file paths (such as C:\\temp\\myfile.txt), this way will work regardless of your OS as long as the relative file structure is the same across the machines.
与显式文件路径(例如C:\\ temp \\ myfile.txt)不同,只要计算机之间的相对文件结构相同,此方法就可以在任何操作系统下工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.