首页 > 解决方案 > 使用 Selenium (Python) 从输出框中获取值

问题描述

我正在尝试根据我在另一个文本框中输入的值提取在文本框中生成的文本。我查看了检查元素,根本没有值的迹象,即使填充了框,“值”也没有任何内容。

我在 Python 中使用 selenium 来尝试执行此操作。我目前只使用 1 个,但将设置一个循环来做数千个,因此我需要这个自动化。

以下是页面中的代码(爱尔兰条例调查网站

<td width="25%" class="form">Latitude:</td>
<td class="form">
   <input type="text" name="GeodeticLatitude" type="number" size="10" maxlength="2" value="">
   deg
   <input type="text" name="GeodeticLatitudeMin" size="2" maxlength="2" value="0">
   min
   <input type="text" name="GeodeticLatitudeSec" size="8" maxlength="8" value="0">
   sec
</td>

下面是我目前正在尝试提取值的代码

browser = webdriver.Chrome()

browser.get("https://gnss.osi.ie/new-converter/")

def find():
    python_button = browser.find_elements_by_xpath("//input[@name='IrishGridEasting']")[0]
    python_button.send_keys("316600")
    python_button = browser.find_elements_by_xpath("//input[@name='IrishGridNorthing']")[0]
    python_button.send_keys("229500")
    python_button = browser.find_elements_by_xpath("//td[@class='form']/button[@type='button']")[1]
    python_button.click()

    latDeg = browser.find_elements_by_xpath("//input[@name='GeodeticLatitude']")
    print(latDeg)

我尝试添加 .text、.getText()、.getAttribute 和 .get_attribute 等选项,但它们不返回文本框值

然后下面的屏幕截图显示了我要检索的内容。

红色框是我要插入的数字,绿色框代表我要提取的内容。

网页截图

标签: pythonpython-3.xseleniumselenium-webdriverselenium-chromedriver

解决方案


您必须提供time.sleep(1),因为生成脚本的值无法同步。尝试WebDriverWait并使用get_attribute('value')从输入字段中获取值。

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
driver=webdriver.Chrome()
driver.get('https://gnss.osi.ie/new-converter/')
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//input[@name='IrishGridEasting']"))).send_keys("316600")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//input[@name='IrishGridNorthing']"))).send_keys("229500")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//tr[contains(.,'Irish Grid Co-ordinates:')]//button[text()='Convert']"))).click()
time.sleep(1)
print(WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.CSS_SELECTOR,"input[name='GeodeticLatitude'][value]"))).get_attribute('value'))

推荐阅读