如何使用 Selenium 和 Python 在文本区域中 send_keys

How to send_keys with in a textarea using Selenium and Python

我需要在现场发送评论。它适用于“输入”,但不适用于“文本区域”。有人必须处理这个问题吗?

在点击 Html 元素之前,它看起来像:

<textarea class = '1' aria-label="Add a comment..." placeholder="Add a comment..."autocomplete="off"  autocorrect="off"> </textarea>

然后:

<textarea class = '1 focus-visible' aria-label="Add a comment..." placeholder="Add a comment..."autocomplete="off"  autocorrect="off" style="height: 18px;"  data-focus-visible-added = ""> </textarea>

textarea 字段已激活,但未添加评论。

browser.find_element_by_css_selector('textarea[placeholder="Add a comment..."]').send_keys('comment')

我不确定你的意思,但对我来说这段代码工作得很好

class Bot():
    def __init__(self):
       self.driver = webdriver.Chrome()
    def comment(self):
       self.driver.get(url)
       self.driver.find_element_by_css_selector('textarea[placeholder="Add a comment..."]').send_keys('comment')

bot = Bot()
bot.comment()

它在我网页的这个元素中写着:

<textarea class = '1' aria-label="Add a comment..." placeholder="Add a comment..."autocomplete="off"  autocorrect="off"> </textarea>

要将 字符序列 发送到 文本区域 ,您必须引入 for the element_to_be_clickable() and you can use either of the following :

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "textarea.1[aria-label^='Add a comment'][placeholder^='Add a comment']"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "textarea.1.focus-visible[aria-label^='Add a comment'][placeholder^='Add a comment'][data-focus-visible-added]"))).send_keys("Алекс")
    
  • 使用XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//textarea[starts-with(@aria-label, 'Add a comment') and starts-with(@placeholder, 'Add a comment')][@class='1']"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//textarea[starts-with(@aria-label, 'Add a comment') and starts-with(@placeholder, 'Add a comment')][@class='1 focus-visible' and @data-focus-visible-added]"))).send_keys("Алекс")
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC