> 文章列表 > wallhaven壁纸下载-selenium版本

wallhaven壁纸下载-selenium版本

wallhaven壁纸下载-selenium版本

「本章我们使用selenium来获取上一章精美的壁纸。上一章的代码,请求的时候会有很多的链接请求不到,具体原因就不追究了,我们本章用selenium来解决一下」

准备工作:
1、驱动(我用的火狐)
2、selenium版本(我用的4.7.2)
3、Python版本(我用的3.9.5)

测试代码能否打开浏览器

url = f'https://wallhaven.cc/hot'
s = Service(r'D:\\pytest_\\Case\\geckodriver.exe')
fox=  webdriver.Firefox(service=s)
fox.get(url)

嗯哼,正常打开,获取其中的属性

ele = fox.find_elements(By.CLASS_NAME,'preview')
for value in ele:value_url = value.get_attribute("href")print(value_url)

可以获取到href属性了,接下里就是再次打开网页。

ele = fox.find_elements(By.XPATH, "//a[@class='preview']")
for value in ele:value_url = value.get_attribute("href")

这样就能获取到全部的图片地址链接了,剩下的就是打开获取高清了

先来看看使用selenium怎么操作

fox.execute_script("window.open('{}')".format(value_url))
for window_handle in fox.window_handles:if window_handle != original_window:fox.switch_to.window(window_handle)breaktry:WebDriverWait(fox, 5).until(EC.presence_of_element_located((By.XPATH, "//*[@id='wallpaper']")))img = fox.find_element(By.XPATH, "//*[@id='wallpaper']").get_attribute('src')img_list.append(img)print(img)except:pass# 关闭新窗口fox.close()# 切换回原始窗口fox.switch_to.window(original_window)

这里大概的意思就是打开新窗口,判断一下,切换新窗口,锁定图片具体链接,获取它。

做完这些操作了,剩下的就是请求了,源码链接我放在了gitee:https://gitee.com/qinganan_admin/reptile-case/blob/master/%E5%A3%81%E7%BA%B8/selenium-wallhaven%E8%8E%B7%E5%8F%96.py

此外,我将获取到的链接储存了一个txt文件,也上传了gitee,有兴趣的可以取看看。