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)
        break
    try:
        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,有兴趣的可以取看看。

目录
相关文章
|
3月前
|
Web App开发 Python
python+selenium+Chrome 监测文件是否下载完毕
python+selenium+Chrome 监测文件是否下载完毕
140 0
|
Web App开发 Windows
Selenium Chrome浏览器版本与chromedriver驱动兼容版本对照表
Selenium Chrome浏览器版本与chromedriver驱动兼容版本对照表
1542 0
Selenium Chrome浏览器版本与chromedriver驱动兼容版本对照表
|
Web App开发
selenium之 chromedriver与chrome版本映射表(更新至v2.43)
selenium之 chromedriver与chrome版本映射表(更新至v2.43)
847 0
|
3月前
|
Web App开发 前端开发 程序员
【 selenium】selenium4新版本使用指南
【 selenium】selenium4新版本使用指南
835 1
|
3月前
|
API Python
python+selenium设置下载路径
python+selenium设置下载路径
101 0
|
3月前
|
API Python
python+selenium设置下载路径21 / 100
python+selenium设置下载路径21 / 100
84 0
|
3月前
设置selenium默认下载位置
设置selenium默认下载位置
226 1
|
Web App开发 Python
Selenium Python 更改 chrome 默认下载目录
关于使用Selenium和Python无法更改Google Chrome默认下载目录的可能问题和解决方法,按照以上步骤,你应该能够成功使用Selenium和Python更改Google Chrome的默认下载目录。
288 0
|
3月前
|
Web App开发 数据采集 IDE
【selenium】selenium4新版本自动获取驱动的常见问题
【selenium】selenium4新版本自动获取驱动的常见问题
453 0
|
3月前
|
Web App开发 Python Windows
Python Selenium 驱动下载与配置使用(详细流程)
Python Selenium 驱动下载与配置使用(详细流程)
414 0

热门文章

最新文章