How to print the partial text from an element using Selenium and Python

安稳与你 提交于 2021-02-05 09:27:45

问题


I am trying to get the text "Album Vol.1 [Every letter I sent you] LP (Normal Edition)" from http://www.ktown4u.com/iteminfo?grp_no=231307&goods_no=44363#dt_wrap01 under the description tab but I keep getting this error message.

selenium.common.exceptions.NoSuchElementException:
Message: no such element: Unable to locate element: 
{"method":"xpath","selector":".//div[@class='view_body']/div[2]/span"}

Different variations give me similar error messages.

driver.find_element_by_css_selector('.view_body>div:nth-child(2)>span')
driver.find_element_by_xpath(".//div[@class='view_body']/div[2]/span")
driver.find_element_by_tag_name('span')

I've also tried driver.implicitly_wait(10) to no avail.


回答1:


With this xpath:

'//div[@id="contents"]/div/div/div[2]/span'

Test in dev tools:

$x('//div[@id="contents"]/div/div/div[2]/span')[0].textContent
"Album Vol.1 [Every letter I sent you] LP (Normal Edition)"



回答2:


To print the text Album Vol.1 [Every letter I sent you] LP (Normal Edition) you you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    driver.get('http://www.ktown4u.com/iteminfo?grp_no=231307&goods_no=44363#dt_wrap03')
    print(re.split('[*\-]',WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.payment-order-list>ul>li"))).text)[1])
    
  • Using XPATH:

    driver.get('http://www.ktown4u.com/iteminfo?grp_no=231307&goods_no=44363#dt_wrap03')
    print(re.split('[*\-]',WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='payment-order-list']/ul/li"))).text)[1])
    
  • Console Output:

    Album Vol.1 [Every letter I sent you] LP (Normal Edition)
    
  • Note : You have to add the following imports :

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


来源:https://stackoverflow.com/questions/62408680/how-to-print-the-partial-text-from-an-element-using-selenium-and-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!