使用 selenium 访问 TextArea

Access TextArea using selenium

我有一个网站 www.example.com,我想从中提取一些特定信息。该网站有一个文本区域占位符,可以在其中添加一些文本。 我正在尝试按如下方式使用硒:

from selenium import webdriver

url = 'https://example.com/'

driver = webdriver.Chrome('my path/chromedriver')
driver.get(url)

获取文本区信息的路径应该是

<body>
  <div class="index-wrap">==[=11=]
...
  <div class="left-s-wrap">
   <div id="table">
    <div class="table">
     <div class="container">
      <div class="table__input"> ==[=11=]
       ... 
       <div class="row tab">
        <div class="table__input-wrap table__input-wrap_multiline">
         <textarea placeholder="https://example.com" wrap="hard" spellcheck="false"></textarea>
          <button class="button button_accent-green">Add URLs</button>

具体要输入url编辑的部分是

         <textarea placeholder="https://example.com" wrap="hard" spellcheck="false">www.my_example.com</textarea>

我想我需要使用 find_element_by_xpath 并单击,类似于此:

        textarea = site.find_element_by_xpath('//textarea')
        textarea.click()

但是我对流程不熟悉,对于使用这些方法访问textarea我是初学者。 对此的任何帮助都将非常有帮助!

更新问题: 虽然我已经按照下面建议的方法进行操作,但我无法提交查询:

from selenium import webdriver
import time

chrome_options = webdriver.ChromeOptions()

driver = webdriver.Chrome('my path/chromedriver',chrome_options=chrome_options)
driver.get('https://www.example.com/')
textarea = driver.find_element_by_xpath('//textarea')
textarea.send_keys("www.my-example.com")

如何点击提交以从网站收集信息?

您需要使用 send_keys 方法将文本发送到文本区域。

textarea = site.find_element_by_xpath('//textarea')
textarea.send_keys("www.example.com")

并且您可以使用这些代码来提取文本区域的值

textarea = site.find_element_by_xpath('//textarea').get_attribute("value")

textarea = site.find_element_by_xpath('//textarea').text

更新: 单击“添加 URL”按钮,您可以使用此 xpath:(假设没有其他按钮具有相同的 class在“添加 URL”按钮之前)

//button[@class='button button_accent-green']

如果在“添加 URL”按钮之前还有其他具有相同 class 的按钮,您可以使用此 xpath。

//button[text()='Add URLs']

所以,点击代码将是:

# with using the class name
button = site.find_element_by_xpath("//button[@class='button button_accent-green']")
# with using the text of the button
button = site.find_element_by_xpath("//button[text()='Add URLs']")
button.click()

您想向该文本区域发送内容吗:

wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, "//textarea[contains(@placeholder, 'https://example.com')]"))).send_keys('some text here ')

这是explicitWait,比find_element_by_xpath

更靠谱

进口:

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

Read more here - official docs