【发布时间】: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