I was unsuccessful in retrieving a text on my python console. Python/Selenium believe it's blank and thus shows Failed to obtain text
(shown in the result image).
Python Code:
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
#Feature: Joke Generator Button
#Scenario: Click button to move onto next jokes.
def test_joke():
#Given the website is displayed with the instruction and button
b=webdriver.Chrome()
b.get("https://elated-benz-84557d.netlify.app/#")
b.implicitly_wait(10)
#When the user clicked on the button
l=b.find_element(By.ID,"next")
l.click()
#Then the joke gets generated
m=b.find_element(By.XPATH,"//*[@id='p']").text
if m == "":
print("Failed to obtain text.")
else:
print(f"The text is: {m}")
b.quit()
test_joke()
Result Below:
The website is a simple joke generator, where initially shows no joke until a button is clicked on. After it's clicked, a joke is generated. I had also attempted with (By.ID, "p")
, other than the XPATH as shown in the code, and had gotten the same failed result.
Below are the images of the webpage before and after clicking the button to generate a joke as well as their respective source code. Highlighted in the HTML is where I had selected the locator of the text, id="p".
Any help is much appreciated. If you have questions, feel free to ask.
CodePudding user response:
After clicking the Next Joke
button there it takes some time to generate a new joke and present it. You have to wait for a text to be visible inside that element.
You are using implicitly_wait
in your code. this will wait for element presence. The better approach is to use Expected Conditions explicitly wait to wait for element visibility, clickability etc. These are much more mature states of a web element that just element presence on the page while element may still not be completely rendered etc.
Please try something like following:
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
#Feature: Joke Generator Button
#Scenario: Click button to move onto next jokes.
def test_joke():
#Given the website is displayed with the instruction and button
b=webdriver.Chrome()
wait = WebDriverWait(b, 20)
b.get("https://elated-benz-84557d.netlify.app/#")
#When the user clicked on the button
wait.until(EC.visibility_of_element_located((By.ID, "next"))).click()
#Then the joke gets generated
m = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id='p']"))).text
if m == "":
print("Failed to obtain text.")
else:
print(f"The text is: {m}")
b.quit()
test_joke()