我尝试使用python编写网络自动化代码,但始终收到错误警告:
selenium.common.exceptions.ElementNotInteractableException:消息:元素不可交互
代码如下:
def commentAndLike():
random.seed()
likeOrNext = random.randint(0, 3)
if likeOrNext == 0:
if check_exists_by_xpath("/html/body/div[3]/div[2]/div/article/div[2]/section[1]/span[1]/button/span"):
likeButton = browser.find_element_by_xpath("/html/body/div[3]/div[2]/div/article/div[2]/section[1]/span[1]/button/span")
likeButton.click()
time.sleep(randomNumber(6, 10))
if check_exists_by_xpath("/html/body/div[3]/div[2]/div/article/div[2]/section[1]/span[2]/button/span"):
random.seed()
randomComment = random.randint(0, 3)
textArea = browser.find_element_by_xpath("/html/body/div[3]/div[2]/div/article/div[2]/section[3]/div[1]/form/textarea")
if randomComment == 0:
textArea.send_keys(comments[0])
elif randomComment == 1:
textArea.send_keys(comments[1])
elif randomComment == 2:
textArea.send_keys(comments[2])
elif randomComment == 3:
textArea.send_keys(comments[3])
time.sleep(randomNumber(15,30))
postButton = browser.find_element_by_xpath("/html/body/div[3]/div[2]/div/article/div[2]/section[3]/div/form/button")
postButton.click()
time.sleep(randomNumber(20,25))
nextButton2 = browser.find_element_by_xpath("/html/body/div[3]/div[1]/div/div/a[2]")
nextButton2.click()
time.sleep(randomNumber(15,20))
else:
nextButton4 = browser.find_element_by_xpath("/html/body/div[3]/div[1]/div/div/a[2]")
nextButton4.click()
time.sleep(randomNumber(20, 25))
else:
nextButton1 = browser.find_element_by_xpath("/html/body/div[3]/div[1]/div/div/a[2]")
nextButton1.click()
time.sleep(randomNumber(20, 25))
else:
nextButton = browser.find_element_by_xpath("/html/body/div[3]/div[1]/div/div/a[2]")
nextButton.click()
time.sleep(randomNumber(20,25))
尝试将send_keys
移至textArea
元素时抛出错误。
我知道我仍然需要改进代码并缩短nextButton的时间,但是我想首先解决问题。谢谢您的帮助!
答案 0 :(得分:0)
根据问题描述进行了修改,其中向textArea
发送密钥会引发错误。
您可以尝试使用Javascript设置textarea的值:
browser.execute_script("arguments[0].value = 'myValue';", textArea)
如果这不起作用,您可以尝试单击textArea首先将其激活:
browser.execute_script("arguments[0].click();", textArea)
browser.execute_script("arguments[0].value = 'myValue';", textArea);
在您的情况下,您可以将'myValue'
替换为' + comments[0] + '
答案 1 :(得分:0)
抛出这种异常是指尽管DOM上存在一个元素,但它并未处于可以交互的状态。您可以尝试实现某种等待机制,最好是这样的显式等待机制:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
textArea = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "/html/body/div[3]/div[2]/div/article/div[2]/section[3]/div[1]/form/textarea"))