0.网址:天工AI—搜索、聊天、写作、速读、画画的全能AI助手 (tiangong.cn)
1.工具:python \selenium、qt等
2、制作界面工具,方便测试
相关代码:
def main():
window = tk.Tk()
window.title("天工小宝宝")
window.geometry("300x200")
# 创建按钮
button_create = tk.Button(window, text="建立工作目录", command=create_work_directory)
button_create.pack()
# 创建按钮
button_open = tk.Button(window, text="准备浏览器环境", command=lambda: open_edge_browser(url))
button_open.pack()
# 测试按钮
button_test = tk.Button(window, text="测试", command=lambda: test())
button_test.pack()
window.mainloop()
def create_work_directory():
# 弹出文件对话框,让用户选择目录
directory = filedialog.askdirectory()
# 获取当前日期和时间
current_time = datetime.now().strftime("%Y%m%d-%H%M%S")
# 创建以当前日期和时间命名的新目录
new_directory = os.path.join(directory, f"tiangong_{current_time}")
os.makedirs(new_directory)
# 在新目录下创建三个文本文件
questions_file = os.path.join(new_directory, "questions.txt")
answers_file = os.path.join(new_directory, "answers.txt")
process_ini_file = os.path.join(new_directory, "process.ini")
with open(questions_file, 'w') as f:
f.write("\n")
with open(answers_file, 'w') as f:
f.write("\n")
with open(process_ini_file, 'w') as f:
f.write("")
# 提示用户工作目录已创建
print(f"工作目录 '{new_directory}' 已创建。")
def open_edge_browser(url):
global driver
# 设置Edge选项
edge_options = Options()
edge_options.use_chromium = True
# 向Edge浏览器传递启动参数
edge_options.add_argument('--disable-extensions') # 禁用浏览器扩展
edge_options.add_argument('--disable-gpu') # 禁用GPU硬件加速
# try:
# driver = webdriver.Edge(find_edge_driver())
# print("EdgeDriver found and initialized.")
# 初始化Edge浏览器驱动(假设msedgedriver.exe已添加到PATH,这儿使用的是自动寻找)
driver = webdriver.Edge(options=edge_options)
driver.maximize_window()
try:
# 打开网页
driver.get(url)
# 设置显式等待,等待页面加载完成
# 这里使用了多个条件来确保页面加载完成:
# 1. `EC.presence_of_element_located((By.TAG_NAME, 'body'))` 确保body标签存在,基本的HTML结构已加载。
# 2. `EC.visibility_of_element_located((By.ID, 'someId'))` 可以替换为页面上某个关键元素的ID,确保该元素不仅加载而且可见。
# 3. `EC.javascript_returned_value(True)` 可以用来执行JavaScript检查`document.readyState`是否为"complete"。
# 通常选择其中一个或几个条件根据实际情况而定,这里以`document.readyState`为例。
WebDriverWait(driver, 10).until(js_condition)
print("网页已加载完成。")
return driver
except Exception as e:
print(f"页面加载超时或发生错误: {e}")
def js_condition(driver):
"""自定义等待条件函数,检查JavaScript返回值"""
return driver.execute_script("return document.readyState") == "complete"
def login_in_tiangong(driver):
# 定位并等待"登录"按钮变为可点击状态
try:
# 这里我们假设"研究"按钮是一个span标签,且class属性为空
yan_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//span[text()='研究']"))
)
# 如果找到了元素并且可点击,可以执行点击操作
yan_button.click()
time.sleep(1)
# 这里我们假设"登录"按钮是一个span标签,且class属性为空
login_button = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//span[text()='登录']"))
)
# 如果找到了元素并且可点击,可以执行点击操作
login_button.click()
print("找到并点击了'登录'按钮")
time.sleep(1)
return True
except Exception as e:
print(f"未能找到或点击'登录'按钮: {e}")
return False
def fill_in_login_form(driver):
# 等待元素出现
login_tab = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, '//div[@id="tab-1" and contains(text(), "账号登录")]'))
)
# 检查元素是否已经具有is-active类
if 'is-active' not in login_tab.get_attribute('class'):
# 如果没有is-active类,添加这个类
login_tab.click()
# 现在元素应该具有is-active类了
print("已将'is-active'类添加到'账号登录'元素")
#填写账号密码
# 等待并定位手机号输入框
phone_number_input = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, '//input[@class="el-input__inner" and @placeholder="请输入手机号"]'))
)
phone_number_input.send_keys("188888888")
# 等待并定位密码输入框
password_input = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, '//input[@class="el-input__inner" and @placeholder="请输入密码"]'))
)
password_input.send_keys("password")
# 定位并点击包含特定文本的div元素
element_to_click = driver.find_element(By.CSS_SELECTOR, 'div.works')
element_to_click.click()
# # 定位登录按钮并点击
# login_button = driver.find_element(By.CSS_SELECTOR, 'button.login-button span')
# 定位登录按钮并点击
login_button = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, '//button[contains(@class, "login-button") and span[text()="登录"]]'))
)
login_button.click()
print("已点击登录按钮")
time.sleep(1)
try:
# 定位验证图片
yanzheng= WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "img.spacesemantic"))
)
while yanzheng:
print ("Waiting for yanzheng")
time.sleep(10)
except Exception as e:
print("exception: " + str(e))
finally:
return True
def test():
# 定位并等待"登录"按钮变为可点击状态
if login_in_tiangong(driver) :
if fill_in_login_form(driver):
print ("登录成功,准备文本录入")
# 定位文本区域
text_area = WebDriverWait(driver, 10).until(
EC.presence_of_element_located(
(By.CSS_SELECTOR, 'textarea.el-textarea__inner'))
)
if text_area:
print("找到了文本框")
text_area.send_keys("测试")
else:
print("没找到文本框")
测试时,文本框可以找到。但文字输入不进去,有什么变通的方法?
File "D:\py_doc2024\kimiauto51\tiangong_cn.py", line 224, in test text_area.click() File "D:\py_doc2024\kimiauto51.venv\Lib\site-packages\selenium\webdriver\remote\webelement.py", line 94, in click self._execute(Command.CLICK_ELEMENT) File "D:\py_doc2024\kimiauto51.venv\Lib\site-packages\selenium\webdriver\remote\webelement.py", line 395, in _execute return self._parent.execute(command, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\py_doc2024\kimiauto51.venv\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 347, in execute self.error_handler.check_response(response) File "D:\py_doc2024\kimiauto51.venv\Lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 229, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <textarea class="el-textarea__inner" tabindex="0" autocomplete="off" placeholder="输入任何想了解的问题,剩下交给AI~" id="el-id-4862-13" style="min-height: 24px; height: 24px;"></textarea> is not clickable at point (981, 349). Other element would receive the click: <div id="aliyunCaptcha-window-popup" class="window-show" style="display: block;">...</div> (Session info: MicrosoftEdge=124.0.2478.80) Stacktrace: GetHandleVerifier [0x009C0483+230755] Microsoft::Applications::Events::time_ticks_t::time_ticks_t [0x00897F91+402
这个错误信息表明在尝试点击文本框时遇到了问题,因为另一个元素(<div id="aliyunCaptcha-window-popup" class="window-show">...</div>)挡在了文本框前面,导致点击事件被拦截。这可能是因为页面上有弹窗或者浮动元素阻碍了点击。要解决这个问题,你可以尝试以下几种方法:
关闭弹窗: 如果这个aliyunCaptcha-window-popup是验证码窗口,尝试找到关闭它的按钮或方法,然后点击关闭。
等待弹窗消失: 使用WebDriverWait等待这个弹窗消失后再进行点击。
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# 等待弹窗消失
WebDriverWait(driver, 10).until_not(
EC.presence_of_element_located((By.ID, "aliyunCaptcha-window-popup"))
)
# 然后点击文本框
text_area.click()
模拟鼠标移动: 在点击文本框之前,模拟鼠标移动到文本框的位置,这有时可以帮助触发页面的JavaScript逻辑,使得点击生效。
# 移动到文本框位置
ActionChains(driver).move_to_element(text_area).perform()
# 然后点击
text_area.click()
使用JavaScript点击: 如果常规的点击方法不起作用,可以尝试使用JavaScript来执行点击操作。
driver.execute_script("arguments[0].click();", text_area)
好吧,把它完善到fill_in_login_form的函数中。
# 定位文本区域
text_area = WebDriverWait(driver, 60).until(
EC.presence_of_element_located(
(By.CSS_SELECTOR, 'textarea.el-textarea__inner'))
)
if text_area:
print("找到了文本框")
# 等待弹窗消失
WebDriverWait(driver, 60).until_not(
EC.presence_of_element_located((By.ID, "aliyunCaptcha-window-popup"))
)
# # 然后点击文本框
# text_area.click()
return True
def test():
# 定位并等待"登录"按钮变为可点击状态
if login_in_tiangong(driver) :
if fill_in_login_form(driver):
print ("登录成功,准备文本录入")
# 使用CSS选择器定位
text_area = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.CSS_SELECTOR,'div[data-v-0db498fc] > textarea.el-textarea__inner'))
)
print ("找到文本框")
# 然后点击
text_area.click()
text_area.clear()
# 输入文本
text_area.send_keys("请推荐一本中国小说,要详细说明推荐理由等,引起我的读书兴趣")
# 添加一个额外的等待,确保文本已经被输入
WebDriverWait(driver, 2).until(
lambda driver: text_area.get_attribute('value') == "请推荐一本中国小说,要详细说明推荐理由等,引起我的读书兴趣"
)
然后就简单了,发送搜索
# 输入文本
text_area.send_keys("请推荐一本中国小说,要详细说明推荐理由等,引起我的读书兴趣")
# 使用CSS选择器定位sendDiv,假设这是搜索按钮
send_div = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, 'div.sendDiv')) # 使用正确的CSS选择器
)
print("找到并点击sendDiv")
# 点击sendDiv
send_div.click()
复制
# 使用CSS选择器定位复制按钮
copy_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, 'svg.svg-btn.copy-Q-DBPvLSU8x > use[xlink:href="#i-copy"]'))
)
# 点击复制按钮
copy_button.click()
全部代码