使用Selenium自动点击国家开放大学个人空间课程
import os
import psutil
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
# 获取已经存在的浏览器实例
for proc in psutil.process_iter():
try:
if "chrome" in proc.name() and "--remote-debugging-port=9223" in proc.cmdline():
chrome_proc = proc
break
except:
pass
else:
# 创建浏览器实例
os.system(r'start chrome --remote-debugging-port=9223 --user-data-dir='D:\评阅用'')
chrome_proc = None
if chrome_proc:
# 连接到已经存在的浏览器实例
webdriver.Remote(command_executor=f"http://localhost:9223", desired_capabilities={})
else:
# 创建新的浏览器实例
options = Options()
options.add_experimental_option("debuggerAddress", "127.0.0.1:9223")
driver = webdriver.Chrome(options=options)
# 查找标签页名称为“国家开放大学个人空间”
target_title = "国家开放大学个人空间"
for handle in driver.window_handles:
driver.switch_to.window(handle)
if target_title in driver.title:
break
# 在网页中查找class属性为<p class="learning_course"> Android智能手机编程# </p>并点击
elements = driver.find_elements_by_css_selector('p.learning_course')
for element in elements:
if element.text.strip() == "Android智能手机编程#":
element.click()
break
该代码使用Selenium库自动打开Chrome浏览器,连接到已有的或新建的浏览器实例,并在国家开放大学个人空间中查找并点击课程“Android智能手机编程”。
代码首先通过遍历系统进程,检查是否存在已有的Chrome浏览器实例,如果存在则连接到该实例,否则创建一个新的浏览器实例。
然后,代码通过遍历浏览器窗口,找到标签页名称为“国家开放大学个人空间”的窗口,并切换到该窗口。
最后,代码使用CSS选择器查找class属性为'learning_course'的元素,并遍历所有匹配的元素,直到找到文本内容为“Android智能手机编程#”的元素,并点击该元素。
注意:
- 代码中的
D:\评阅用路径需要根据实际情况进行修改。 - 该代码仅供学习参考,实际使用时需要根据具体需求进行调整。
- 为了保证代码的正常运行,请确保已安装Selenium库。
- 请确保您已在Chrome浏览器中开启了“开发者工具”,并启用了“远程调试”。
原文地址: https://www.cveoy.top/t/topic/f2MA 著作权归作者所有。请勿转载和采集!