【问题标题】:Python Selenium Get All "href" attributesPython Selenium 获取所有“href”属性
【发布时间】:2019-06-13 08:07:15
【问题描述】:

如何在this page 上获取此“h2”标题的所有“href”属性?

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

我试过的没有得到href,是:

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

这没有得到“a”标签的链接。如果我在“a”标签上查找所有元素,它将返回页面上的每个href(这不是我想要的)。我想只返回上面的标题,但能够获取它们的 url“href”属性。

【问题讨论】:

    标签: python selenium href


    【解决方案1】:

    这里的代码从所有页面获取所有书籍:

    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)
    

    【讨论】:

      【解决方案2】:

      Selenium 可能对您的需要有点过头了,好的旧 BeautifulSoup 也可以解决问题。

      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"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-22
        • 2020-02-28
        • 2016-04-18
        • 1970-01-01
        • 1970-01-01
        • 2011-04-21
        • 1970-01-01
        相关资源
        最近更新 更多