1.获取文心一言的登录cookie(60秒内登录后等待程序自动退出即可),并将其保存在本地txt文档中,代码如下:
import json
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
driver=webdriver.Edge() #默认打开Edge浏览器
driver.maximize_window() #设置全屏
driver.get("https://yiyan.baidu.com/")
driver.delete_all_cookies()
sleep(60)
#将cookies保存在本地cookies.txt中
get_cookies=json.dumps(driver.get_cookies())
f=open("cookies.txt","w")
f.write(get_cookies)
driver.close()
2.获取完毕后进入下一个程序:
from selenium import webdriver
import json
from time import sleep
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.options import Options
print("请等待初始化...")
try:
#开启无头模式
#web=webdriver.Edge()
edge_options = Options()
edge_options.add_argument("--headless")
edge_options.add_argument('--no-sandbox')
edge_options.add_argument('--disable-dev-shm-usage')
edge_options.add_argument("--window-size=1920,1080")
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 S```afari/537.36'
edge_options.add_argument(f'user-agent={user_agent}')
web=webdriver.Edge(options=edge_options)
#阻止反爬虫,借鉴csdn
web.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
})
"""
})
web.get("https://yiyan.baidu.com/")
web.delete_all_cookies()
f=open("cookies.txt","r")
listcookie=json.loads(f.read())
for cookie in listcookie:
web.add_cookie(cookie)
f.close()
web.refresh() #此时已经登录文心一言
#等待两秒防止js还未刷新出来
sleep(2)
except:
print("初始化失败!")
exit(0)
print("初始化成功")
while True:
question=web.find_element(By.CLASS_NAME,"yc-editor-paragraph")
question.send_keys(input("请输入您想要问的问题:"))
sleep(0.5)
confirm=web.find_element(By.CLASS_NAME,"VAtmtpqL")
confirm.click()
sleep(2)
while True:
if confirm.is_displayed():
x=web.find_element(By.CLASS_NAME,"custom-html")
print(x.text)
break
else: continue
目前只是初始版,没有加入更多的功能了。