0

I'm trying to get the Facebook link from a website href element, but keep getting errors. Here is the HTML from its website:

   <li class="ssi-facebook">
      <a href="http://www.facebook.com/pages/YMCA-of-Central-Massachusetts/165183010213237?sk=wall" target="_blank" rel="noopener noreferrer">
      </a>
    </li>

and here is the code I've tried:

elems = WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located(
        (By.CLASS_NAME, 'ssi-facebook')))
links = [elem.get_attribute('href') for elem in elems]
print(links)

Do you have any idea how to solve this?

Josh
  • 35
  • 1
  • 6

2 Answers2

0

An li tag does not have an href attribute, an a tag does.

You can use the below CSS selector instead

elems = WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'li.ssi-facebook a')))
links = [elem.get_attribute('href') for elem in elems]
print(links)
JeffC
  • 22,180
  • 5
  • 32
  • 55
cruisepandey
  • 28,520
  • 6
  • 20
  • 38
0

There are a couple of things to consider:

  • The href link is within the child A of the parent LI

  • As you are dealing with only one element instead of element(s) you can look for the unique element.

  • To print the href attribute, as the desired element is a element i.e. a clickable element instead of presence_of_element_located() you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "li.ssi-facebook > a[href]"))).get_attribute("href"))
    
  • Using XPATH:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//li[@class='ssi-facebook']/a[@href]"))).get_attribute("href"))
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 1
    Thank you for your help. Now I am more understanding about getting attributes using css selector. I really appreciate it. – Josh Dec 10 '21 at 16:59