Selenium python click on coordinate

Selenium python click on coordinate

For example, some page elements are difficult to obtain,But the location is very fixed,Then you can directly use coordinates to operate

For example, to operate on (x:200, y:100) on the page,You can use the following code:

from selenium import webdriver from selenium.webdriver.common.action_chains import actionchains dr=webdriver.chrome () dr.get ("http://www.google.com") actionchains (dr) .move_by_offset (200, 100) .click (). perform () #left mouse click, 200 is the x coordinate and 100 is the y coordinate actionchains (dr) .move_by_offset (200, 100) .context_click (). perform () #Right-click 

Running effect (right click):

have to be aware of is,Each movement is based on the previous coordinates (that is, the coordinate values ​​are cumulative). When the code above actually runs,After clicking left and right click,The coordinates will become (400, 200).

You can use the package to offset this accumulation (restore the mouse coordinates after clicking), the code is as follows:

from selenium import webdriver from selenium.webdriver.common.action_chains import actionchains def click_locxy (dr, x, y, left_click=true): "" " dr:browser x:page x coordinate y:page y coordinate left_click:true is the left mouse click. Otherwise right click "" " if left_click: actionchains (dr) .move_by_offset (x, y) .click (). perform () else: actionchains (dr) .move_by_offset (x, y) .context_click (). perform () actionchains (dr) .move_by_offset (-x, -y) .perform () #Restore the mouse position to before moving if __name__ == "__main__": dr=webdriver.chrome () dr.get ("http://www.google.com") click_locxy (dr, 100, 0) #left click click_locxy (dr, 100, 100, left_click=false) #right click 

Источник

Читайте также:  Структура нейронной сети python

Python. Кликаем по координатам (WebScrapping) [6]

Думал что закончил с Selenium, как выяснилось нет. Поэтому выйдет еще пару статей по данной библиотеке.

Предисловие.

В данном уроке мы научимся кликать по координатам окна с помощью Selenium. Данная возможность будет полезна, при написании ботов для онлайн игр.

Приступаем.

Для работы с мышью нам потребуется модуль ActionChains.

ActionChains — это модуль позволяющий производить низкоуровневые операции такие как:

При вызове методов класса ActionChains, методы помещаются в очередь. Вызываются они методом perform(), в порядке очереди. Подробнее в документации.

Рисуем точку на экране.

from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains driver = webdriver.Chrome('chromedriver.exe') driver.set_window_size(500, 500) driver.get('http://paintonline.editaraudio.com/') ActionChains(driver).move_by_offset(250, 250).click().perform()

Сохраните данный код, поместив в одной папке с chromedriver.exe (браузер Google Chome должен быть установлен). Разберем код.

from selenium.webdriver.common.action_chains import ActionChains

Импортируем ActionChains

driver.set_window_size(500, 500)

Устанавливаем размер окна браузера в 500×500 пикселей.

driver.get('http://paintonline.editaraudio.com/')
ActionChains(driver).move_by_offset(250, 250).click().perform()

Здесь мы делаем последовательность действий.

В итоге, мы нарисовали точку на экране.

Рисуем 2 точки на экране.

Добавьте следующие строки к себе в код:

ActionChains(driver).reset_actions() ActionChains(driver).move_by_offset(250, 300).click().perform()

Здесь, мы сбросили положение курсора reset_actions(), теперь положение равно 0,0. Затем, кликнули по координатам (250, 300) тем самым, нарисовав точку на холсте.

Чертим линию на экране.

Удалите предыдущие вызовы ActionChains, и добавьте следующий.

ActionChains(driver).move_by_offset(250, 250).click_and_hold().move_by_offset(20, 20).perform()
  • move_by_offset(250, 250) — передвигаем курсор на координаты 250, 250
  • click_and_hold() — зажимаем ЛКМ
  • move_by_offset(20, 20) — двигаем курсор на 20 пикселей вправо, и 20 вниз, на координаты 270, 270.
  • perform() — выполняем все действия.

В итоге, получилась диагональная линия.

Заключение

Используя ActionChains, можно написать бота, практически, для любой игры.

Начиная от кликеров, по типу alien worlds.

Заканчивая фермами, с возможностью drag_and_drop.

Источник

Selenium python click on coordinate

For example, some page elements are difficult to obtain, but the position is very fixed, so you can directly use coordinates to operate.
For example, to operate on (x:200, y:100) on the page, you can use the following code:

from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains dr = webdriver.Chrome() dr.get('http://www.baidu.com') ActionChains(dr).move_by_offset(200, 100).click().perform() # Left mouse click, 200 is the x coordinate, 100 is the y coordinate ActionChains(dr).move_by_offset(200, 100).context_click().perform() # 

Run effect (right click):

It should be noted that each movement is based on the previous coordinate (that is, the coordinate value is cumulative). When the above code is actually running, click the left button and then right click, the coordinates will become (400, 200). .

You can use the package to offset this accumulation (the mouse coordinates are restored after clicking), the code is as follows:

from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains def click_locxy(dr, x, y, left_click=True): ''' Dr: browser x: page x coordinate y: page y coordinate Left_click: True is left mouse click, otherwise right click ''' if left_click: ActionChains(dr).move_by_offset(x, y).click().perform() else: ActionChains(dr).move_by_offset(x, y).context_click().perform() ActionChains(dr).move_by_offset(-x, -y).perform() # Restore the mouse position to before moving if __name__ == "__main__": dr = webdriver.Chrome() dr.get('http://www.baidu.com') click_locxy(dr, 100, 0) # Left click click_locxy(dr, 100, 100, left_click=False) # right click 

Источник

Русские Блоги

Python + селен нажмите на указанные координаты на веб-странице

Например, некоторые элементы страницы трудно получить, но позиция очень фиксированная, поэтому вы можете напрямую использовать координаты для работы
Например, для работы с (x: 200, y: 100) на странице вы можете использовать следующий код:

from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains dr = webdriver.Chrome() dr.get('http://www.baidu.com') ActionChains(dr).move_by_offset(200, 100).click().perform() # Левый клик мыши, 200 - координата x, 100 - координата y ActionChains(dr).move_by_offset(200, 100).context_click().perform() # Правой кнопкой мыши 

Эффект операции (правая кнопка):

Следует отметить, что каждое движение основано на последней координате (то есть значение координаты является кумулятивным). Когда приведенный выше код фактически выполняется, нажмите левую кнопку и затем щелкните правой кнопкой мыши, координаты станут (400, 200) ,

Вы можете использовать инкапсуляцию для компенсации этого накопления (координаты мыши будут восстановлены после щелчка), код выглядит следующим образом:

from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains def click_locxy(dr, x, y, left_click=True): ''' Dr: браузер x: страница x координата y: координата страницы y left_click: True - щелчок левой кнопкой мыши, в противном случае - щелчок правой кнопкой мыши. ''' if left_click: ActionChains(dr).move_by_offset(x, y).click().perform() else: ActionChains(dr).move_by_offset(x, y).context_click().perform() ActionChains(dr).move_by_offset(-x, -y).perform() # Восстановите положение мыши, прежде чем двигаться if __name__ == "__main__": dr = webdriver.Chrome() dr.get('http://www.baidu.com') click_locxy(dr, 100, 0) # Щелчок левой кнопкой мыши click_locxy(dr, 100, 100, left_click=False) # щелкните правой кнопкой мыши 

Источник

How to Click on WebElement & Current Location in Selenium

Scientech Easy

In the previous tutorial, we understood the basics of actions class and action interface in Selenium WebDriver.

We also learned different types of methods available under the action interface and actions class.

If you have not been familiarized with the different types of methods of actions class, I will recommend you to look at a glance.

You will get a list of all methods under actions class in a very simple way.

Now, let’s come to the main topic. In this tutorial, we will learn how to click at current location and WebElement using actions class methods in Selenium WebDriver.

How to Click at Current Location in Selenium?

To click on the current location, we will use click() method of actions class. The click() method is used to the left-clicking of the mouse at its current location.

Let’s automate a scenario related to it.

Scenario to Automate:

In this scenario, we will assume that the Gmail element on the Google home page is a current location.

1. Launch the Firefox web browser.
2. Open a URL of the Google home page.
3. Locate the element “Gmail” on the home page using By.xpath.
4. Find the location and coordinate (x, y) of Gmail WebElement.
5. Move the mouse cursor from its initial position to the current location.
6. Now, click on the current location (i.e on Gmail element).
7. Close the web browser.

Let’s see the following source code related to the above scenario. Follow all the steps in the below source code.

Program source code 1:

package seleniumProject; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; public class ClickAtCurrentLocation < public static void main(String[] args) < // Create a driver object of Firefox browser. WebDriver driver = new FirefoxDriver(); // Maximize the browser. driver.manage().window().maximize(); // Create a variable URL to store the URL of Google home page. // Since the return type of URL is String, we will declare URL as String type. String URL = ”https://www.google.com”; // Call get() method of WebDriver and pass URL as a parameter. driver.get(URL); // Wait for some time to load. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Locate the element “Gmail” by By.xpath. WebElement Gmail = driver.findElement(By.xpath(“//a[text()=’Gmail’]”)); // Create an object of Actions class and pass reference variable driver as a parameter to its constructor. Actions actions = new Actions(driver); // Get the location and Coordinate (x, y) of WebElement “gmail”. Call getLocation(), getX(), and getY() methods to find the location and coordinate. int getX = gmail.getLocation().getX(); System.out.println(“X coordinate: ” +getX); int getY = gmail.getLocation().getY(); System.out.println(“Y coordinate: ” +getY); // Call moveByOffset() method of Actions class to move the mouse cursor from initial position to given Offset. // Pass the coordinates of x and y as parameters to moveByOffset() method. actions.moveByOffset(getX+1, getY+1).click(); actions.build().perform(); System.out.println(“Clicked Successfully on Gmail”); driver.close(); >>
Output: X coordinate: 1285 Y coordinate: 19 Clicked Successfully on Gmail

Explanation:

1. In the above source code, the statement gmail.getLocation().getX(); has been used to find the location and x coordinate of the location of Gmail WebElement.

2. getY() method with a combination of getLocation() has been used to find y coordinate of the location of Gmail WebElement. The coordinate (x, y) of the Gmail element is nothing but Offset that is the location of Gmail.

3. moveByOffset() method is used to move the mouse cursor from point (0, 0) to point of Gmail element. Note that the initial position of the mouse cursor is (0, 0).

4. After calling moveByOffset() method, we passed the Offset as parameters to the method. +1 in both parameters is added because the initial position is starting from the coordinate (0, 0). That’s why we will have to add +1 to get the exact location of WebElement.

5. Now, click() method of actions class is called to click on the element.

6. actions.build().perform(); is used to perform the chain of actions and clicking.

How to Click on WebElement in Selenium WebDriver?

In the previous section, we have learned to click on WebElement by calculating its offset. This technique is not used every time, especially, when the WebElement has its own attribute such as ID or name.

In this case, we can use another overloaded version of click() method to click directly on any WebElement. The syntax of overloaded click() method to click on web element is as follows:

public Actions click(WebElement onElement)

This method takes an input parameter as an instance of WebElement on which the click action has to be performed.

Now, let us modify the following previous code of above scenario to use click(WebElement element) method. In this coding, we will not use moveByOffset() method.

Program source code 2:

package seleniumProject; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; public class ClickOnWebElementDirectly < public static void main(String[] args) < // Create a driver object of Firefox browser. WebDriver driver = new FirefoxDriver(); // Maximize the browser. driver.manage().window().maximize(); // Create a variable URL to store the URL of Google home page. Since the return type of URL is String, we will declare URL as String type. String URL = "https://www.google.com"; // Call get() method of WebDriver and pass URL as a parameter. driver.get(URL); // Wait for some time to load. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Locate the element “Gmail” by By.xpath. WebElement gmail = driver.findElement(By.xpath(“//a[text()='Gmail']”)); // Create an object of Actions class and pass reference variable driver as a parameter to its constructor. Actions actions = new Actions(driver); actions.click(gmail); actions.build().perform(); System.out.println(“Clicked Successfully on Gmail”); driver.close(); >>
Output: Clicked Successfully on Gmail

As you can see in this coding that the moveByOffset() method has been replaced with click(WebElement onElement) method and the complex coordinate geometry has been removed from the coding.

So, if you are a tester, tell your developers to provide attributes for the WebElement. The task will be easy.

Hope that this tutorial has covered almost all important points related to how to click at current location and WebElement in Selenium using Actions class. I hope that you will have understood and learned to click on WebElement using click() method of actions class.

In the next tutorial, we will learn how to double-click at current location and WebElement in Selenium WebDriver.
Thanks for reading.
Next ⇒ How to perform double click action in Selenium ⇐ PrevNext ⇒

Источник

Оцените статью