Home > Back-end >  Get href value, not href anchor text, by CSS Selector
Get href value, not href anchor text, by CSS Selector

Time:10-07

I am using Selenium to pull first instances of hrefs from multiple classes of the same name, but can't seem to return the href value. I've only been able to succeed in returning the href's anchor text.

Here's where I'm at:

pages = driver.find_elements_by_css_selector(".elementor-widget-container > [href]:nth-of-type(1)")
for page in pages:
     data.append({
     "Location Page": page
     })
print(data)

Both "a" and "[href]" work in returning the anchor text. I'm sure I need to be more specific, but I'm too unfamiliar with CSS Selectors to use the proper syntax.

Much thanks for any advice.

CodePudding user response:

You can get the href of an element by using element.get_attribute('href') like shown below.

pages = driver.find_elements_by_css_selector(".elementor-widget-container > [href]:nth-of-type(1)")
for page in pages:
     data.append({
     "Location Page": page.get_attribute('href')
     })
print(data)
  • Related