userPyGeo
userPyGeo

Reputation: 3971

Python Selenium Get All "href" attributes

How will I get all the "href" attributes for this "h2" titles on this page?

<h2 class="entry-title">
<a href="http://www.allitebooks.com/deep-learning-with-python-2/" rel="bookmark">Deep Learning with Python</a>
</h2>

What I have tried doesn't get the href, is:

title = driver.find_elements_by_class_name('entry-title')
title[0].get_attribute('href')

This did not get the links for "a" tag. And if I do a find all elements on "a" tag, it will return every href on the page (which isn't what I wanted). I want to return just the titles as above but be able to get their url "href" attributes.

Upvotes: 2

Views: 1623

Answers (2)

Sers
Sers

Reputation: 12255

Here code getting all books from all pages:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
baseUrl = "http://www.allitebooks.com/page/1/?s=python"
driver.get(baseUrl)

# wait = WebDriverWait(driver, 5)
# wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".search-result-list li")))

# Get last page number
lastPage = int(driver.find_element(By.CSS_SELECTOR, ".pagination a:last-child").text)

# Get all HREFs for the first page and save them in hrefs list
js = 'return [...document.querySelectorAll(".entry-title a")].map(e=>e.href)'
hrefs = driver.execute_script(js)

# Iterate throw all pages and get all HREFs of books
for i in range(2, lastPage):
    driver.get("http://www.allitebooks.com/page/" + str(i) + "/?s=python")
    hrefs.extend(driver.execute_script(js))

for href in hrefs:
    print(href)

Upvotes: 3

Niles
Niles

Reputation: 351

Selenium might be overkill for what you need, good old BeautifulSoup will do the trick as well.

import urllib.request, bs4
body = urllib.request.urlopen(urllib.request.Request("http://www.allitebooks.com/page/1/?s=python", headers={"User-Agent": "Mozilla"})).read().decode("utf-8")
soup = bs4.BeautifulSoup(body)
for element in soup.find_all("h2", class_="entry-title"):
    for link in element.find_all("a"):
        print(link.get("href"))

Upvotes: 1

Related Questions