Home > Software engineering >  Get element value and compare using Python and Selenium
Get element value and compare using Python and Selenium

Time:10-05

hi this is my first time with Python and Selenium so please be patient.

I have:

<span id="map_x" class="gr een">36</span>
<span id="map_y" class="green">3</span>

So now I'm trying to comapare this value like that

mapx = window.find_element_by_xpath("/html/body/div[6]/div[57]/div[1]/h1/span[2]")
mapy = window.find_element_by_xpath("/html/body/div[6]/div[57]/div[1]/h1/span[3]")
while int(mapx.get_attribute('value')) != 1 and int(mapy.get_attribute('value')) <= 40:

I want to do a loop while mapx is not 1 and mapy less than 40 but when I'm trying it:

Traceback (most recent call last):
  File "C:\Users\", line 50, in <module>
    while int(mapx.get_attribute('value')) != 1 and int(mapy.get_attribute('value')) <= 40:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

I will be grateful for any help i was trying many other ways, but it still doesn't working.

CodePudding user response:

Its a valid error. The span tag has no attribute value to extract from get_attribute(). It has only id and class attributes. And if it does not find, it will return None.

You need extract the text from those span tags and compare. Try like below and confirm:

1: You can use .text to extract text from a tag.

while int(mapx.text) != 1 and int(mapy.text) <= 40:

2: You can use get_attribute(innerText) too.

mapx = window.find_element_by_xpath("/html/body/div[6]/div[57]/div[1]/h1/span[2]")
mapy = window.find_element_by_xpath("/html/body/div[6]/div[57]/div[1]/h1/span[3]")
while int(mapx.get_attribute('innerText')) != 1 and int(mapy.get_attribute('innerText')) <= 40:

Instead of Absolute xpath opt for Relative xpaths. If Elements id are unique you can try like below:

mapx = window.find_element_by_id("map_x")
mapy = window.find_element_by_id("map_y")
# OR

mapx = window.find_element_by_xpath("//span[@id='map_x' and @class='gr een']")
mapy = window.find_element_by_xpath("//span[@id='map_y' and @class='green']")

CodePudding user response:

You should use .text if this does not work we can work with get_attribute

do this :

mapx = window.find_element_by_xpath("/html/body/div[6]/div[57]/div[1]/h1/span[2]")
mapy = window.find_element_by_xpath("/html/body/div[6]/div[57]/div[1]/h1/span[3]")
while int(mapx.text) != 1 and int(mapy.text) <= 40:
    do while loop logic here

Also not sure if we have unique id map_x and map_y in HTMLDOM, if we have for

<span id="map_x" class="gr een">36</span>
<span id="map_y" class="green">3</span>

if it happens to be unique in nature, please use

window.find_element_by_id('map_x')

similarly for other elements as well.

  • Related