python - BeautifulSoup 选择具有特定类的某些元素中的所有 href

标签 python html selenium web-scraping beautifulsoup

我正在尝试从 this 中删除图像网站。我尝试使用 Scrapy(使用 Docker)和 scrapy/slenium。 Scrapy 似乎不适用于 windows10 home,所以我现在尝试使用 Selenium/Beautifulsoup。我正在 Anaconda 环境中使用带有 Spider 的 Python 3.6。

这就是我需要的 href 元素的样子:

<a class="emblem" href="detail/emblem/av1615001">

我有一个重大问题:
- 我应该如何使用 Beautifulsoup 选择 href?在我的代码下面,您可以看到我尝试过的内容(但没有成功)
- 由于可以观察到 href 只是 url 的部分路径...我应该如何处理这个问题?

这是我到目前为止的代码:

from bs4 import BeautifulSoup
from time import sleep
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import urllib 
import requests
from os.path  import basename


def start_requests(self):
        self.driver = webdriver.Firefox("C:/Anaconda3/envs/scrapy/selenium/webdriver")
        #programPause = input("Press the <ENTER> key to continue...")
        self.driver.get("http://emblematica.grainger.illinois.edu/browse/emblems?Filter.Collection=Utrecht&Skip=0&Take=18")
        html = self.driver.page_source

        #html = requests.get("http://emblematica.grainger.illinois.edu/browse/emblems?Filter.Collection=Utrecht&Skip=0&Take=18")
        soup = BeautifulSoup(html, "html.parser")        
        emblemshref = soup.select("a", {"class" : "emblem", "href" : True})

        for href in emblemshref:
            link = href["href"]
            with open(basename(link)," wb") as f:
                f.write(requests.get(link).content)

        #click on "next>>"         
        while True:
            try:
                next_page = self.driver.find_element_by_xpath("//a[@id='next']")
                sleep(3)
                self.logger.info('Sleeping for 3 seconds')
                next_page.click()

                #here again the same emblemshref loop 

            except NoSuchElementException:
                #execute next on the last page
                self.logger.info('No more pages to load') 
                self.driver.quit()
                break 

最佳答案

您可以通过类名获取 href:

que1:

for link in soup.findAll('a', {'class': 'emblem'}):
   try:
      print link['href']
   except KeyError:
      pass`

关于python - BeautifulSoup 选择具有特定类的某些元素中的所有 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47653309/

相关文章:

python - 在模板中显示 Django 外键值

Python:动态区间数据结构

Python 语法 : Subprocess Call PostgreSQL Query, "Error: Only ASCII Characters Allowed"

html - CSS 移动布局

python - 如何使用 Selenium 切换到 #shadow-root (open) 内的子框架

python - 如何在 Windows 上安装 PyCrypto?

html - 如何在 <tr> 中居中对齐 <td>?

html - 在表单中包含额外的 HTTPS 请求 header 信息

api - WebDriver Selenium API : identifying a WebElement in XPath

javascript - 在 Windows 7 上安装 Selenium(ChromeDriver, Javascript) 时出现问题