How to retrieve partial text from a text node using Selenium and Python

别来无恙 提交于 2020-06-23 12:21:11

问题


I want to get only " text ... " not using .split() or index slicing

HTML:

<a class="call_recipe" href="/recipes/2913">
      " text ... "
      <strong> something~ </strong>
    </a>

HTML Snapshot:


回答1:


To print text ... you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR and childNodes:

    print(driver.execute_script('return arguments[0].firstChild.textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "a.call_recipe[href^='/recipes']")))).strip())
    
  • Using XPATH and splitlines():

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@class='call_recipe' and starts-with(@href, '/recipes')]"))).get_attribute("innerHTML").splitlines()[1])
    
  • 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
    



回答2:


driver.find_element_by_class_name("call_recipe").text

I think this is what you're after.

How to get text with selenium web driver in python




回答3:


you can utilize the

 "find_element_by_class_name("some_text").getText()"

or to better match the text you can use

"driver.find_element_by_xpath("..").text"

Hope this is helpful



来源:https://stackoverflow.com/questions/62445850/how-to-retrieve-partial-text-from-a-text-node-using-selenium-and-python

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