python - Selenium 不起作用?

标签 python selenium bots

最近我一直在用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/

相关文章:

python - python 中的字典 : summing the values returned from searching the keys

python - SQLAlchemy:如何正确使用group_by()(only_full_group_by)?

在给定谓词为真的元素之后拆分列表的 Pythonic 方法

java - 如何在 Selenium 中设置 Chrome 的设置能力?

python - Discord.py Bot 将文件发送到 Discord channel

python - 如何在涉及 if 语句的 python 中返回三个元组

java - Selenium 自动化组织项目

ruby-on-rails - 如何使用DatabaseCleaner[:active_record].策略=:与 Selenium 的交易

python - 通过 webhooks 中的 slack 提及用户

python - python 上的简单 XMPP 机器人