The Find Element Returns Empty String..Using Xpath Contains,Text()

Python Selenium: Finds element but returns empty string

You can use this code:- Moreover, you can change the sleep timing as per your need. for your information, this code gives error sometimes because the list is pretty dynamic. But you can run it again to get the full player list.

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

driver = webdriver.Chrome()
action = ActionChains(driver)

driver.get('https://earthmc.net/map/')

wait = WebDriverWait(driver, 20)
time.sleep(20)

ExpandArrow = wait.until(EC.visibility_of_element_located((By.XPATH, '//div[@class="hitbar"]')))
action.move_to_element(ExpandArrow).perform()

PlayerList = driver.find_elements_by_xpath('//li[contains(@class,"player")]')

for element in PlayerList:
driver.execute_script("arguments[0].scrollIntoView();", element)
print(element.text)

print("Successfully Completed.")

Note - If this is what you are looking for then mark this as the answer.

XPATH Testing string value of child and parent has empty string value

//span[text()='630']/parent::div[not(text())]

try this.

I want to pass my test if the element in selenium returns empty text

You can make use of .isEmpty() or .equals("") in conjunction like below

for (int i = 1; i <= noPriorityPageTotal; i++) {
List<WebElement> allListofNoPriority = driver.findElements(By.xpath("(//*[@class='sortable-row'])[" + i + "]//td[3]"));
for (WebElement element : allListofNoPriority) {
// logger.info("The text is "+ element.getText());
if (element.getText().isEmpty() || element.getText().equals("")) {
System.out.println("Test case should be pass");
}
else {
System.out.println("Test case should be fail.");
}
}
}

in case you are TestNg as a test automation framework, you can use assertion as below :

for (int i = 1; i <= noPriorityPageTotal; i++) {
List<WebElement> allListofNoPriority = driver.findElements(By.xpath("(//*[@class='sortable-row'])[" + i + "]//td[3]"));
for (WebElement element : allListofNoPriority) {
// logger.info("The text is "+ element.getText());
if (element.getText().isEmpty() || element.getText().equals("")) {
System.out.println("Test case should be pass");
logger.info("The text is "+ element.getText());
Assert.assertTrue(true);
}
else {
System.out.println("Test case should be fail.");
logger.info("The text is "+ element.getText());
Assert.assertTrue(false);
}
}
}

WebElement getText() returning empty string even though element is visible

After much (much) troubleshooting it turned out that I had a slight mistake on my Xpath. From my html

<div id="QosDashboardPanel0" ...

I was not accounting for multiple tabs. In my AUT I was opening a new tab, not a new browser tab but a tab in the application itself, and the whole Hmtl would remain the same except the snippet above would change to

<div id="QosDashboardPanel1" ...

I was assuming that the ID wouldn't change, well lesson learned! This is why I was running into the 'not able to click an invisible element', the element was in fact there but it was hidden behind my active tab.

Not much of a solution but I hope if someone is running into something similar this at least points them in the correct direction or makes a bell go off.

xpath selector returns empty values

basically that's marquee in HTML5, so you have to explicitly wait for each elements.

Code :

driver = webdriver.Chrome(driver_path)
driver.maximize_window()
driver.implicitly_wait(50)
driver.get("https://www.rrpcanada.org/#/")
wait = WebDriverWait(driver, 50)
try:
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[class$='unset-margin']"))).click()
except:
pass

elements = driver.find_elements(By.XPATH, "//div[contains(@class, 'marquee-text-text')]//descendant::span[@class='bold']")
for ele in elements:
wait.until(EC.visibility_of(ele))
print(ele.text)
new_ele = ele.find_element_by_xpath(".//following-sibling::span")
wait.until(EC.visibility_of(new_ele))
print(new_ele.text)

Output :

"C:\Program Files\Python39\python.exe" C:/Users/****/PycharmProjects/SeleniumSO/Chrome.py
Surgical & Reusable Masks:
1,215,028,138 units
Surface Wipes:
56,023,303 units
Gowns and Coveralls:
22,899,306 units
Respirators:
11,732,566 units
Face Shields:
4,731,581 units
Hand Sanitizer:
527,672 L
Surface Solutions:
48,337 L
Ventilators:
500 units
Thermometers:
6,922 units
Testing Kits:
22,205 units
Disposable Gloves:
137,455,881 units
Surgical & Reusable Masks:
1,215,028,138 units
Surface Wipes:
56,023,303 units
Gowns and Coveralls:
22,899,306 units
Respirators:

cannot get empty string to list from Xpath

This script will iterate over each item and if there isn't any price, it replaces it with N/A:

import requests
import lxml.html


def parse_data(url):
try:
response = requests.get(url)
except:
return
tree = lxml.html.document_fromstring(response.text)
for item in tree.xpath('//*[contains(@class, "list-item-details")]'):
title = item.xpath(".//h2/a/text()")[0]
price = item.xpath('.//*[contains(@class, "price")]/text()')
price = price[0] if price else "N/A"

print("{:<40} {:<20}".format(title, price))

def main():
url = "https://www.avbuyer.com/aircraft/private-jets/page-13"
parse_data(url)


if __name__ == "__main__":
main()

Prints:

Dassault Falcon 50EX                     Deal pending        
Cessna Citation M2 Please call
Embraer Phenom 300 Please call
Bombardier Learjet 40XR Please call
Embraer Legacy 600 Please call
Cessna Citation Sovereign Price: USD $6,500,000
Cessna Citation Ultra Please call
Cessna Citation Ultra Please call
Airbus ACJ318 Make offer
Gulfstream G550 Please call
Boeing 737 -500 Please call
Boeing BBJ Make offer
Hawker 800XP Please call
Boeing 737 Price: USD $3,500,000
Bombardier Learjet 55 Please email
Bombardier Challenger 300 Make offer
Airbus ACJ TwoTwenty N/A
Gulfstream G200 Please call
Bombardier Learjet 60XR Deal pending
Cessna Citation Mustang Price: USD $1,200,000

getting next sibling node value/text returns empty string

thanx to @CBroe comment , here is how i did it

        $hList =  $nodes[0]->getElementsByTagName('h3');

foreach ($hList as $k=>$h )
{
$h_text = $h->nodeValue ;
dump($h_text);

$current_el = $h ;
$current_nodeName = $current_el->nodeName ;

while ($current_nodeName != 'p')
{

$current_el = $current_el->nextSibling ;
$current_nodeName = $current_el->nodeName ;
}

$p_text = $current_el->nodeValue;
dd($p_text);
}


Related Topics



Leave a reply



Submit