使用Python从输入框复制文本并保存到变量中

2 投票
3 回答
4523 浏览
提问于 2025-04-18 17:43

我想知道怎么用Selenium获取没有值属性的输入框里的文本。问题是这些输入框在页面加载时会自动填充(可能是用JavaScript填的),而这些文本在HTML里并没有显示出来,所以我找不到任何能代表它的东西。

image

3 个回答

0

你可以自己实现一个期望条件。下面的代码可以正常工作。

html/js:

<html>
<head>
<script type="text/javascript" >
    window.onload = function(){
        document.getElementById("string").value = "hello";
    };
</script>
</head>
<body>
        <input id="string" type="text" value="">

</body>
</html>

python:

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

class regex_to_be_present_in_element_value(object):
    def __init__(self, locator, regex):
        self.locator = locator
        self.regex = regex

    def __call__(self, driver):
        try:
            element_text = EC._find_element(driver,
                                         self.locator).get_attribute("value")
            if element_text:
                return re.match(self.regex, element_text)
            else:
                return False
        except StaleElementReferenceException:
                return False

driver = webdriver.Firefox()
driver.get("file:///path/to/the/htmlfile.html")
try:
    element = WebDriverWait(driver, 10).until(
        regex_to_be_present_in_element_value((By.ID, "string"), "he*")
    )
finally:
    driver.quit()

这个代码的作用是等待,直到指定元素的值属性中有文本出现,并且这个文本符合传给构造函数的正则表达式。在这个例子中,正则表达式是“hello”。“he*”可以匹配“hello”。

我在制作这个类的时候参考了这个指南:https://selenium.googlecode.com/git/docs/api/py/_modules/selenium/webdriver/support/expected_conditions.html#text_to_be_present_in_element_value

1

一旦文本放进了这个框里,你可以通过 WebElement.get_attribute('value') 来获取它。这里的 WebElement 就是你想要提取文本的那个文本框。

2

我使用了一个叫做 win32clipboard 的模块,这个模块是 pywin32 的一部分,解决了我的问题。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import win32clipboard

element.send_keys(Keys.CONTROL, 'a') #highlight all in box
element.send_keys(Keys.CONTROL, 'c') #copy

win32clipboard.OpenClipboard()
text = win32clipboard.GetClipboardData() #paste
win32clipboard.CloseClipboard()

print text

撰写回答