使用Selenium在Python中连接Gemini网络聊天
我正在尝试用Python中的Selenium连接到Gemini的网页聊天,目的是想实现这篇Medium文章中描述的功能。
我试着使用了以下代码:
from selenium import webdriver
from selenium.webdriver.firefox.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
def send_message(prompt):
options = Options()
options.headless = True
driver = webdriver.Firefox(options=options)
try:
driver.get("https://gemini.google.com")
# Assuming there is a login process, you may need to automate login here
# Wait for the text area to be clickable and visible
text_area = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, 'rich-textarea > div > p'))
)
text_area.send_keys(prompt)
# Find and click the send button
send_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, 'div[class*="send-button-container"] > button'))
)
send_button.click()
# Wait for the response to appear
WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, 'message-content[class*="model-response-text"]'))
)
# Find the response element
response_element = driver.find_element(By.CSS_SELECTOR, 'message-content[class*="model-response-text"]')
# Get the text from the response element
response_text = response_element.text
return response_text
finally:
driver.quit()
def main():
# Prompt user for what to ask Gemini
prompt = input("Ask Gemini: ")
response_text = send_message(prompt)
print("\nResponse from Gemini:")
print(response_text)
if __name__ == "__main__":
main()
但是,它出现了一个TimeoutException
的错误,提示信息是:我不太确定是什么原因导致这个问题。任何帮助或建议都将非常感激。
selenium.common.exceptions.TimeoutException: Stacktrace: RemoteError@chrome://remote/content/shared/RemoteError.sys.mjs:8:8 WebDriverError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:192:5 NoSuchElementError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:510:5 dom.find/</<@chrome://remote/content/shared/DOM.sys.mjs:136:16
1 个回答
0
检查浏览器兼容性 确保你使用的Chrome WebDriver版本和你电脑上安装的Chrome浏览器版本是匹配的。如果版本不一致,可能会导致一些意想不到的问题或者兼容性上的麻烦。