Home > Net >  Having problem getting text with Selenium WebDriver in Python
Having problem getting text with Selenium WebDriver in Python

Time:06-10

I am trying to get text from this site using Selenium WebDriver and here is my code.

from os import system
from selenium import webdriver
driver = webdriver.Chrome("./chromedriver")
driver.get("http://www.lutanho.net/play/hex.html")

msgbox = driver.find_element_by_css_selector("body > div > form > table > tbody > tr > td:nth-child(5) > table > tbody > tr:nth-child(9) > td > table > tbody > tr:nth-child(3) > td > input")
msg = msgbox.text

print(msg)

I want to get the message in the selected box. I expect the value of msg would become something likes " Red to move." or " Blue has won !". However, the result of msg is empty, indicating that msg did not get any value from msg = msgbox.text.

I wonder why msg does not change every time when I execute a move?

By the way, I have check this similar problem, but it did not help in my case.

CodePudding user response:

The problem you have is that, since the text is in an input and not a normal element you need to get the text by calling msg = msgbox.get_attribute('value') because that's where the text is stored in the html.

PS: To have it updating you need to re-set the msg variable to msgbox.get_attribute('value') after you make a move, each time you make a move.

CodePudding user response:

The other option is return that value by executing:

msg = driver.execute_script("return window.document.OptionsForm.Msg.value")
  • Related