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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清安无别事

慢慢的积累一杯奶茶吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值