Nika Tvildiani Nika Tvildiani - 1 year ago 71
Python Question

Selenium click trouble (Python)

I am using Selenium (

) to automate a chess site but I am having trouble clicking on a piece and moving it. I have tried
but nothing is working. Here is my code:

from selenium import webdriver
from import By
from import WebDriverWait
from import expected_conditions as EC

T = r"C:\Users\HP\Downloads\chromedriver.exe"
options = webdriver.ChromeOptions()
Driver = webdriver.Chrome(T, chrome_options=options)
Piece = WebDriverWait(Driver,10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="chessboard_boardarea"]/img[22]')))

When I run the script nothing happens but the white pawn should be highlighted in yellow. Can someone explain why
is not working? How can I make it work?

P.S. If solution requires JavaScript help, please write it in more detail because I don't know JavaScript at all.

Answer Source

This is somewhat complicated. The chess pieces are IMGs that can be clicked but empty chess squares are not represented by an element. You will have to determine a coordinate system and use move_to_element_with_offset(to_element, xoffset, yoffset) based off the board represented by <div id="chessboard_boardarea" ...> and the board labels A-H and 1-8. For move_to_element_with_offset(), the offsets are relative to the top-left corner of the element. So in this case, (0,0) is the top left corner of the chessboard.

The code below should click the white pawn at A2 and then click A3 which moves it. The board is 640px x 640px. Each square is 80px. The code is clicking in the middle of the square so:

  • A8 would be 40,40
  • A1 is 40,600
  • H8 is 600,40
  • H1 is 600,600

board = Driver.find_element_by_id("chessboard_boardarea")
action_chains = ActionChains(Driver)
action_chains.move_to_element_with_offset(board, 40, 520).click().perform() # A2
action_chains.move_to_element_with_offset(board, 40, 440).click().perform() # A3

You can determine what piece is represented by an element (IMG tag) by looking at the filename in the src attribute. For example, src="//" has the filename bn.png and is the black knight. Each image filename will be two letters. The first letter is the piece color which is either 'b' for black or 'w' for white. The second letter is the piece name, 'p' pawn, 'r' rook, 'n' knight, 'b' bishop, 'q' queen, and 'k' king. So, bn.png is 'b' for black and 'n' for knight... the black knight.

You can determine where pieces are by using the transform: translate(160px, 160px); portion of the style attribute of the IMG tags representing the different pieces. For example, transform: translate(160px, 160px); this element is at 160,160 which is C6 (the coords are the top-left of the square and each square is 80px).