Mixter
Mixter

Reputation: 193

Access html text through python selenium

I am trying to get text (marked by hashtags).

<div class="XYZ">
        <h5>
    "
          #######Reports due by##############
    "
          <span class="hbl" data-hint="task due date">
            <i class="icon-boxy-sign"></i>
          </span>
        </h5>
        <script type="jsv#61^"></script><script type="jsv#123_"></script>
        <script type="jsv#60^"></script><script type="jsv#124_"></script>
      <script type="jsv#59^"></script><p>#################07/10/2020#######################</p><script type="jsv/125^"></script>
    <script type="jsv/52_"></script><script type="jsv/24^"></script>
        <script type="jsv/42_"></script><script type="jsv/23^"></script>
      </div>

Python line to get the text inside the hashtags:

txt = dat =wait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'div[class="XYZ"]'))).text

I expect the line to print: "Reports due by" and "07/10/2020, I keep getting timeoutException and Unable to locate element errors.

Upvotes: 2

Views: 178

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193058

Seems you were close. To extract the text (marked by hashtags) you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.XYZ"))).get_attribute("title"))
    
  • Using XPATH:

    print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='XYZ']"))).get_attribute("title"))
    
  • 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
    

Here you can find a relevant discussion on selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element while trying to click Next button with selenium

Upvotes: 1

IPolnik
IPolnik

Reputation: 649

Change By. CSS_SELECTOR to By.XPATH and update locator to '//div[@class='XYZ']'. Should work.

Upvotes: 0

Related Questions