简体   繁体   中英

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>

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

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:

     大塊文化 

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM