#ecoding=gbk
from selenium import webdriver
# 文件目录
import os
# 时间
import time
# 随机User-Agent
from fake_useragent import UserAgent
import requests
from loguru import logger
from selenium.webdriver.common.action_chains import ActionChains
import pyautogui
ua = UserAgent(verify_ssl=False)
headers = {
"Cookie": "_ga=GA1.2.929478863.1645602135; _gid=GA1.2.114174532.1646029429; Hm_lvt_768a5f0e1e2da152800f053cec2f560a=1645602133,1646029427,1646099330; Hm_lpvt_768a5f0e1e2da152800f053cec2f560a=1646101802"
,
"User-Agent": ua.random
}
options = webdriver.ChromeOptions()
# 浏览器不提供可视化页面
#options.add_argument("--headless")
driver = webdriver.Chrome(options=options)
# 获取当前目录
root = os.getcwd()
@logger.catch()
def get_img_data(url, num, code):
# 请求地址
driver.get(url)
# 等待2秒
driver.implicitly_wait(2)
# 获取图片组编码
img_code = driver.current_url.split("/")[-1]
# 获取图片组名称
img_name = driver.find_element_by_xpath("/html/body/section[1]/div/main/article/h1").text
# 进入当前目录
os.chdir(root)
os_path_file = f"{img_code}_{img_name}"
if not os.path.exists(os_path_file):
os.mkdir(f"{os_path_file}")
os.chdir(f"{os_path_file}")
# 获取图片地址
img_src = driver.find_element_by_xpath("/html/body/section[1]/div/main/article/figure/img").get_attribute('src')
logger.info(f"{img_src}")
# 保存到本地
#response2 = requests.get(img_src, headers=headers, verify=False)
#response2.encoding="utf-8"
#with open(f"{num}.jpg","wb") as f:
# f.write(response2.content)
#time.sleep(1)
#num = num + 1
#得到边界值
img_end = driver.find_element_by_xpath("/html/body/section[1]/div/main/div[1]/div[2]/div/div[2]").text
logger.info(f"{img_end}")
if img_end != '没有了':
logger.info("还有")
# 浏览器打开新窗口
newwindow = f'window.open("{img_src}")'
driver.execute_script(newwindow)
# 切换到新窗口
driver.switch_to_window(driver.window_handles[1])
# 移动到该元素
pic = driver.find_element_by_xpath("/html/body/img")
action = ActionChains(driver).move_to_element(pic)
action.context_click(pic) # 右键点击该元素
action.perform() # 执行
pyautogui.typewrite(['v']) # 敲击V进行保存
# 单击图片另存之后等1s敲回车
time.sleep(1)
pyautogui.typewrite(['enter'])
#driver.close();
# 切回原窗口
#driver.switch_to_window(driver.window_handles[0])
#img_name2 = driver.find_element_by_xpath("/html/body/section[1]/div/main/article/h1").text
#logger.info(f"{img_name2}")
# next_label = driver.find_element_by_xpath("/html/body/section[1]/div/main/article/figure/div[3]")
# next_label.click()
#detail_index(img_data_set)
@logger.catch()
def run():
# 开始的地址
url = '***'
get_img_data(url, 0, 138)
# 启动方法
if __name__ == '__main__':
run()
Python 点击元素以及切换窗口另存文件代码小计
于 2022-03-03 09:32:28 首次发布