当前位置:   article > 正文

python用selenium模拟浏览器点击页面某个按钮_python selenium 点击按钮

python selenium 点击按钮

步骤:

1. 将chromedriver.exe(https://chromedriver.storage.googleapis.com/index.html?path=2.35/)下      载放到Python文件夹里面

2. 运行命令安装Selenium

pip install Selenium==3.3.1

3. 创建代码

根据要求书写:打开页面-点击banner广告-返回上一页-刷新页面

  1. from selenium import webdriver
  2. from selenium.webdriver.common.by import By
  3. from selenium.webdriver.support.ui import WebDriverWait
  4. from selenium.webdriver.support import expected_conditions as EC
  5. # 初始化Chrome浏览器
  6. driver = webdriver.Chrome()
  7. # 打开指定的URL
  8. driver.get("website_address")
  9. while True:
  10. # 刷新页面
  11. driver.refresh()
  12. print("Refreshed page")
  13. # 等待页面加载完成
  14. wait = WebDriverWait(driver, 10)
  15. element_ad = wait.until(EC.presence_of_element_located((By.XPATH, '//*
  16. [@id="advertViewDom"]/uni-view/uni-swiper/div/div[1]/div/uni-swiper-item[1]/uni-
  17. view/uni-image[1]')))
  18. # 确保广告是可见的
  19. if element_ad.is_displayed():
  20. # 点击广告
  21. element_ad.click()
  22. print("Clicked on ad")
  23. else:
  24. print("Ad is not visible")
  25. # 尝试返回上一页
  26. try:
  27. driver.back()
  28. print("Returned to previous page")
  29. except Exception as e:
  30. print(f"Failed to go back: {e}")
  31. # 如果不在首页,跳出循环
  32. if driver.current_url != "website_address":
  33. break

p.s. 如何找到XPath?

打开chrome,F12,找到需要点击的元素,右键copy-copy 

4. 运行脚本

python text.py

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/896656
推荐阅读
相关标签
  

闽ICP备14008679号