hakukou
hakukou

Reputation: 111

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>

Upvotes: 3

Views: 3391

Answers (4)

RegCent
RegCent

Reputation: 108

You could also use

driver.find_element_by_css_selector('span[translate="no"]')

CSS Selectors should be faster than XPath

EDIT Edited per DebanjanB comment - thank you

Upvotes: 0

undetected Selenium
undetected Selenium

Reputation: 193048

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:

    大塊文化
    

Upvotes: 1

NarendraR
NarendraR

Reputation: 7708

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

Upvotes: 1

KunduK
KunduK

Reputation: 33384

Try the following code.

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

driver.get("https://www.kobo.com/tw/zh/ebook/NXUCYsE9cD6OWhvtdTqQQQ")
element=WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'a.description-anchor span[translate="no"]')))
print(element.text)

Upvotes: 0

Related Questions