import os
import psutil
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 检查是否已经存在浏览器实例,如果存在则不再创建
for proc in psutil.process_iter():
    try:
        if 'chrome' in proc.name() and '--remote-debugging-port=9223' in proc.cmdline():
            break
    except:
        pass
else:
    # 创建浏览器实例
    os.system(r'start chrome --remote-debugging-port=9223 --user-data-dir="D:\评阅用"')

# Chrome选项
options = Options()
options.add_experimental_option('debuggerAddress', '127.0.0.1:9223')

# 连接到已存在的浏览器实例
driver = webdriver.Chrome(options=options)

# 查找标签页名称为'国家开放大学个人空间'
target_tab = None
for tab in driver.window_handles:
    driver.switch_to.window(tab)
    if '国家开放大学个人空间' in driver.title:
        target_tab = tab
        break

# 切换到目标标签页
if target_tab:
    driver.switch_to.window(target_tab)
else:
    print('未找到目标标签页!')

# 在网页中查找class属性为<p class='learning_course'> Android智能手机编程# </p>并点击
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, 'p.learning_course'))
    )
    if 'Android智能手机编程#' in element.text:
        element.click()
        print('已点击目标元素!')
    else:
        print('未找到目标元素!')
except:
    print('查找目标元素时出错!')

# 关闭浏览器
driver.quit()
Python Selenium自动化:连接现有Chrome浏览器、查找标签页并点击指定元素

原文地址: https://www.cveoy.top/t/topic/f2MJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录