1、前期准备
我们此次需要的python库有selenium、pyautogui,
pip install selenium
pip install pyautogu

2.导入相关库

from selenium import webdriver
import time
import re
from selenium.webdriver.common.action_chains import ActionChains
import pyautogui
4、声明并调用浏览器,打开网页,自动搜索
  browser = webdriver.Chrome()
  url = 'https://wallhaven.cc/'
  browser.get(url)

 

   之后应该会自动打开这个页面,我们想做的是自动输入图片名称,然后点击小放大镜,所以我们应该需要先获得这两个元素,获得元素的方式大概有以下几种:
 find_element_by_name
  find_element_by_id
  find_element_by_xpath
  find_element_by_link_text
  find_element_by_partial_link_text
  find_element_by_tag_name
  find_element_by_class_name
  find_element_by_css_selector

 

  我们首先把光标放到元素上,然后右键-检查(Chrome浏览器),就可以定位到相应的代码下,然后右键-COPY-COPY XPATH(也可以COPY其他方式)。
  我这里利用id和xpath分别获得输入框和搜索按钮两个元素。
   input_ = browser.find_element_by_id('search-text') #获取输入框元素
  input_.send_keys('Makise Kurisu') #输入要搜索的名称
  time.sleep(2) #睡两秒
  button_ = browser.find_element_by_xpath('//*[@id="startpage-search"]/div/button') #获取搜索按钮元素
  button_.click() #进行点击
   之后浏览器就会自动进行输入和搜索~
  5、获取每张图片的预览点击链接,并自动进入每张图片进行右键-保存
  text = browser.page_source # 获取页面信息
  pattern = re.compile(r'<a class="preview" href="(.*?)" target="_blank">')
  res = re.findall(pattern,text) # 正则表达式匹配

 

  首先获取每个图片的预览链接,这里我利用正则去获取,也可以利用xpath等方式。
  for i in res:
  browser.get(i) # 进入链接
  time.sleep(3)
  pic = browser.find_element_by_xpath('//*[@id="wallpaper"]') # 获取元素
  action = ActionChains(browser).move_to_element(pic)  # 移动到该元素
  action.context_click(pic)  # 右键点击该元素
  action.perform() # 执行
  pyautogui.typewrite(['v']) # 敲击V进行保存
  # 单击图片另存之后等1s敲回车
  time.sleep(1)
  pyautogui.typewrite(['enter'])

 

  之后就是遍历每一个url,进行右键-保存操作,具体可以看代码~注释很详细。
  PyAutoGUI是一个纯Python的GUI自动化工具,可以用程序自动控制鼠标和键盘操作,我利用Selenium尝试自动右键保存多次无果,采用了这个方式,也是很顺利完成了。(如果有Selenium可以自动右键并回车的方式务必分享一下~~)
  6、总结
  至此算是正式结束了,接下来放上所有代码
  from selenium import webdriver
  import time
  import re
  from selenium.webdriver.common.action_chains import ActionChains
  import pyautogui
  browser = webdriver.Chrome()
  url = 'https://wallhaven.cc/'
  browser.get(url)
  input_ = browser.find_element_by_id('search-text') #获取输入框元素
  input_.send_keys('Makise Kurisu') #输入要搜索的名称
  time.sleep(2) #睡两秒
  button_ = browser.find_element_by_xpath('//*[@id="startpage-search"]/div/button') #获取搜索按钮元素
  button_.click() #进行点击
  text = browser.page_source # 获取页面信息
  pattern = re.compile(r'<a class="preview" href="(.*?)" target="_blank">')
  res = re.findall(pattern,text) # 正则表达式匹配
  for i in res:
  browser.get(i)
  time.sleep(3)
  pic = browser.find_element_by_xpath('//*[@id="wallpaper"]')
  action = ActionChains(browser).move_to_element(pic)  # 移动到该元素
  action.context_click(pic)  # 右键点击该元素
  action.perform() # 执行
  pyautogui.typewrite(['v']) # 敲击V进行保存
  # 单击图片另存之后等1s敲回车
  time.sleep(1)
  pyautogui.typewrite(['enter'])
  time.sleep(10)
  browser.close()