1引入相关库
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import json
2.这里以b站为例,这里使用cookie登录b站,用其他方式登录也可
#d访问bilibili
url = 'https://www.bilibili.com/'
driver = webdriver.Chrome()
driver.get(url)
driver.maximize_window()
#使用cookies进行登录
with open(r'D:tem\001\bilili_cookies.txt','r') as f:cookie_list = json.load(f)for cookie in cookie_list:driver.add_cookie(cookie)
driver.refresh()
3.然后进入回复界面,并跳转窗口至新打开的回复界面
#进行窗口跳转
main_windown = driver.current_window_handle
handle = driver.window_handles
driver.switch_to.window(handle[-1])
4获取输入框和发送按钮两个元素并发送一次消息检验是否成功
#进行窗口跳转
#输入框元素和发送按钮获取并检验正确性
text_input_bear = driver.find_element(By.XPATH,'//*[@id="editor"]')
text_bear_button = driver.find_element(By.XPATH,'//*[@id="link-message-container"]/div[1]/div[2]/div[2]/div[1]/div/div/div[5]/div[1]/div[4]/div[3]/button')
text_input_bear.send_keys('贞德士妮娅')
text_bear_button.click()
5登录gpt网站,同样的手动进入回复界面并先发文几个问题,并同样获取输入框元素和发送按钮元素
#登录网站
driver1 = webdriver.Chrome()
driver1.get('https://www.sharexbar.com/chatgpt-web-main/')
#窗口转移
driver1.maximize_window()
handle = driver1.window_handles
driver1.switch_to.window(handle[-1])
6定义等待函数,分别是等待私信中的好友发的信息文本函数,以及等待gpt回答的元素,并返回文本及答案。
#元素等待
def test_text_change(timeout,frequency):if timeout < frequency:return 'ERROR timeout is less than frequency'seconds = 0list_len = len(driver.find_elements(By.CSS_SELECTOR,'div.not-me > div.message > div.message-content'))while seconds <= timeout:message_text_list1 = driver.find_elements(By.CSS_SELECTOR,'div.not-me > div.message > div.message-content')list1_len = len(message_text_list1)print('等待好友发问中!')if list1_len == list_len:time.sleep(frequency)seconds+=frequencyelse:print('问:')print(message_text_list1[-1].text)return message_text_list1[-1].textreturn False
#等待gpt进行回答
def wait_gpt_answer(timeout,frequency):if timeout < frequency:return 'ERROR timeout is less than frequency'seconds = 0answer_len = len(driver1.find_elements(By.CLASS_NAME,'markdown-body'))while seconds <= timeout:answer1 = driver1.find_elements(By.CLASS_NAME,'markdown-body')answer1_len = len(answer1)print('等待gpt回答中')if answer1_len == answer_len:time.sleep(frequency)seconds+=frequencyelse:print('gpt答:')print(answer1[-1].text)return answer1[-1].textreturn False
这里涉及到多个重复元素的问题,所以取最后一个。但之所以没使用WebDriverWait等库,是因为暂时没找到对应的方法。
7定义发送函数,分别是回复界面的和gpt发问界面的函数
#获取好友回答内容发送至gpt问答区
def sent_text_gpt():text = test_text_change(60,5)if text != False:print('发送一次问题至gpt')input_gpt.clear()input_gpt.send_keys(text)button_gpt.click()
#获取gpt回答发送给私信好友
def sent_text_bilili():tt = wait_gpt_answer(75,20)if tt != False:print('发送一次私信')text_input_bear.clear()text_input_bear.send_keys(tt)text_bear_button.click()
8调用函数,最后退出
for i in range(5):sent_text_gpt()sent_text_bilili()
driver1.quit()
driver.quit()
9效果如图