Issue
I have the following HTML snippet and discovered how to get to the text (a date and time) with the following Xpath in Chrome. However, with Selenium, using find_element_by_xpath doesn't work because it needs to grab an element. It also doesn't work if I get the Xpath to capture the react-text comment. Also, tried grabing the top div tag and then doing an [element].text, but that is not seeing the date/time text. How can I grab that date/time so it is usable in my Selenium script. Thank you very much.
//div[@data-list-index='0']/div/div/div/div[@aria-colindex = '8']/div/span[2]/following-sibling::text()
Solution
You can try like this
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('your_website_url')
parent_element = driver.find_element_by_xpath("//div[@data-list-index='0']/div/div/div/div[@aria-colindex='8']/div/span[2]")
date_time_text = driver.execute_script("return arguments[0].childNodes[0].textContent;", parent_element)
print(date_time_text)
To ByPass or Avoid UnicodeError
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('your_website_url')
parent_element = driver.find_element_by_xpath("//div[@data-list-index='0']/div/div/div/div[@aria-colindex='8']/div/span[2]")
date_time_text = driver.execute_script("""
const parent = arguments[0];
let text = '';
for (const node of parent.childNodes) {
if (node.nodeType === Node.TEXT_NODE) {
text += node.textContent.replace(/[^\x00-\x7F]/g, ''); // Exclude non-ASCII characters
}
}
return text.trim();
""", parent_element)
print(date_time_text)
Answered By - Mahboob Nur
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.