如何使用Python Selenium拖放文件? [英] How to drag and drop file with Python Selenium?

查看:189
本文介绍了如何使用Python Selenium拖放文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一下我的测试(硒/ python),以便在网站上创建新图像。我需要为其加载图片。当我可以选择使用放置或文件浏览器字段时,该怎么办。据我所知,我无法使用文件浏览器,因为没有ID或名称。如何使用拖放方法?

I would like to check in my test (selenium / python) creating a new image on the site. I need to load a picture for it. How can I do this when I have the option to use the drop or file explorer field. As far as I know, I can not use the file explorer because there is no id or name. How to use the drag and drop method?

我有以下代码,但无法正常工作:

I have this code but it does not work:

element = driver.find_elements_by_id ("file_upload")
element.send_keys ( "C: \\ Users \\ Desktop \\ Robert \\ Construct_ImminentCollision-C.jpg")
target = driver.find_element_by_id ("add-new-pano")

action_chains = ActionChains (driver)
action_chains.drag_and_drop (element, target) .perform ()

add-new-pano是放置字段ID。

"add-new-pano" is the drop field id.

推荐答案

虽然我最近没有使用过硒,但是如果您在静态工作区中工作,则可以控制大多数我建议使用的 PyAutoGUI 。这不是动态解决方案,但确实包含左鼠标模拟拖放功能

While I haven't used selenium recently, if you're working in a static workspace where you can control most everything I would recommend using PyAutoGUI. It isn't a dynamic solution, but it does contain a left mouse emulation feature for drag and drop.

在提供的示例中,鼠标从100,100位置向屏幕底部移动了100像素:

In the provided example, the mouse moves from the 100,100 location towards the bottom of the screen by 100 pixels:

>>> pyautogui.moveTo(100,100)    #starting mouse location of 100,100
>>> pyautogui.dragTo(100,200, button='left')     # drag mouse to X of 100, Y of 200 while holding down left mouse button

$ b $将鼠标拖动到X为100,Y为200 b

如果每次知道文件浏览器的分辨率,位置等即可在受控环境中完成,则可以为应用程序设置临时解决方案。

You can setup a makeshift solution to your application if it can be done in a controlled environment every time where you know the resolution, location of the file explorer, etc.

我在Windows env中遇到了问题。之前由于意外的更新屏幕。令人回味的食物...

I have run into issues in a windows env. before due to unexpected update screens. Food for thought...

这篇关于如何使用Python Selenium拖放文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆