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

后端 未结 3 640
梦毁少年i
梦毁少年i 2020-12-12 05:38

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

HTML:


      \" text ...          


        
3条回答
  •  無奈伤痛
    2020-12-12 05:58

    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, childNodes and strip():

      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, get_attribute() 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
      

    References

    You can find a couple of relevant detailed discussions in:

    • How to get text from textnodes seperated by whitespace using Selenium and Python

提交回复
热议问题