【问题标题】:BeautifulSoup select all href in some element with specific classBeautifulSoup 选择具有特定类的某些元素中的所有href
【发布时间】:2018-05-19 02:18:04
【问题描述】:

我正在尝试从this 网站上删除图像。我尝试使用 Scrapy(使用 Docker)和 scrapy/slenium。 Scrapy 似乎在 windows10 家庭中不起作用,所以我现在正在尝试使用 Selenium/Beautifulsoup。我在 Anaconda 环境中使用 Python 3.6 和 Spider。

这就是我需要的 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 

【问题讨论】:

  • 能否把你的第二个问题说得更清楚些。
  • 嗨!由于我必须在单击图像时下载图像,所以我得到以下link。在 href 中只有一个真实路径href="detail/emblem/av1615001"。这是我解析href时的问题吗?
  • 如果 http://emblematica.grainger.illinois.edu/ 部分不变,那么您可以将其用作常量,例如:BASE_URL = "emblematica.grainger.illinois.edu" ,然后将此前缀添加到每个 href。

标签: python html selenium web-scraping beautifulsoup


【解决方案1】:

你可以通过类名来获取href:

que1:

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

【讨论】:

  • soup.findAll('a', {'class': 'emblem'}) 我找到了所有&lt;a&gt; elem。 &lt;a class="emblem" href="detail/emblem/av1615018"&gt; &lt;img src="http://emblemimages.grainger.illinois.edu/UtrechtVols/huygens.knaw.nl_3Aemitx_3Aav1615/JPGthumbnail/pictura/av1615018.jpg"/&gt; &lt;p class="font-16"&gt;EIICE PRIMVM TRABEM&lt;/p&gt; &lt;/a&gt;。当我尝试print link['href'] 时,出现以下错误:TypeError: string indices must be integers
【解决方案2】:

试试这个。它将为您提供遍历该站点中所有页面的所有 url。我使用了Explicit Wait 使其更快、更动态。

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
from bs4 import BeautifulSoup

driver = webdriver.Chrome()
url = "http://emblematica.grainger.illinois.edu/"
wait = WebDriverWait(driver, 10)
driver.get("http://emblematica.grainger.illinois.edu/browse/emblems?Filter.Collection=Utrecht&Skip=0&Take=18")
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".emblem")))

while True:
    soup = BeautifulSoup(driver.page_source,"lxml")
    for item in soup.select('.emblem'):
        links = url + item['href']
        print(links)

    try:
        link = driver.find_element_by_id("next")
        link.click()
        wait.until(EC.staleness_of(link))
    except Exception:
        break
driver.quit()

部分输出:

http://emblematica.grainger.illinois.edu/detail/emblem/av1615001
http://emblematica.grainger.illinois.edu/detail/emblem/av1615002
http://emblematica.grainger.illinois.edu/detail/emblem/av1615003

【讨论】:

    【解决方案3】:

    不确定上述答案是否有效。这是为我工作的一个。

    url = "SOME-URL-YOU-WANT-TO-SCRAPE"
    response = requests.get(url=url)
    urls = BeautifulSoup(response.content, 'lxml').find_all('a', attrs={"class": ["YOUR-CLASS-NAME"]}, href=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      相关资源
      最近更新 更多