Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the text within the element using Selenium WebDriver and Python?

Grab the text of the specified area.

Website: https://www.kobo.com/tw/zh/ebook/NXUCYsE9cD6OWhvtdTqQQQ.

Image:

https://imgur.com/a/qK1uA9L

Code:

BookTitle = driver.find_elements_by_xpath('//p[@class="title product-field"]')
BookTitle[0].getWindowHandle() 

HTML:

<span translate="no">大塊文化</span>
like image 462
hakukou Avatar asked Feb 03 '26 19:02

hakukou


2 Answers

To extract the text 大塊文化 from the specified area you need to induce WebDriverWait for the visibility_of_element_located() and you can use the following solution:

  • Code Block:

    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
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_argument("--disable-extensions")
    options.add_argument('disable-infobars')
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get('https://www.kobo.com/tw/zh/ebook/NXUCYsE9cD6OWhvtdTqQQQ')
    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h2[text()='電子書詳細資料']//following::ul[1]//li/a[@class='description-anchor']/span"))).text)
    driver.quit()
    
  • Console Output:

    大塊文化
    
like image 189
undetected Selenium Avatar answered Feb 06 '26 07:02

undetected Selenium


You are doing in wrong way :

BookTitle[0].getWindowHandle() not suppose to do anything here

Simply try :

driver.find_element_by_css_selector("a[class='description-anchor']>span").text
like image 27
NarendraR Avatar answered Feb 06 '26 09:02

NarendraR