最近我一直在用Python做一个项目。这是一个聊天机器人。 但当他们断开连接时,代码似乎就停止了。并且不继续运行。这是为什么?
from selenium import webdriver
import random
import time
chrome_path = r"C:\Users\isak\Downloads\chromedriver_win32\chromedriver.exe"
with open('omegle_test_bot.txt', 'r') as words:
read = words.read()
words = read.split('\n')
driver = webdriver.Chrome(chrome_path)
driver.get('http://www.omegle.com/')
interests = driver.find_element_by_class_name('newtopicinput')
interests.send_keys('programming\npython\nsoundcloud\nhigh\nweed\n')
time.sleep(7)
driver.find_element_by_xpath("""//*[@id="videobtn"]""").click()
time.sleep(2)
def if_disconnect():
time.sleep(1)
driver.find_element_by_class_name('disconnectbtn').click()
Main()
def Main():
while True:
text_box = driver.find_element_by_class_name('chatmsg')
word = random.choice(words)
text_box.send_keys(random.choice(words))
driver.find_element_by_class_name('sendbtn').click()
Main()
if_disconenct()
最佳答案
问题是您的代码永久发送消息,无需任何等待:您搜索输入字段,发送键,搜索按钮,一遍又一遍地单击按钮...当您的访客断开连接时,他会触发页面刷新,并在某个时刻您的代码无法找到输入字段或按钮并且脚本停止。您可能需要使用显式等待
来等待元素变得可用,然后再尝试处理它:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
text_box = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "chatmsg")))
text_box.send_keys(random.choice(words))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "sendbtn"))).click()
另请注意,这段代码 word = random.choice(words)
不执行任何操作(您不会在代码中使用 word
变量)。
因为你的main()
没有条件停止运行(不包含break
),所以不可能运行if_disconect()
...曾经
关于python - Selenium 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41491929/