使用 Selenium 和 python 在 'div' 中插入文本

Insert text inside 'div' with Selenium and python

关于使用 selenium 将文本插入 div 标签,您还有什么想法吗?下面是我的例子。 我想在 div 标签

之间插入一些长字符串

这个例子行得通,但是字符串很长,它会永远持续下去。

text_area.clear()
text_area.send_key(very_long_string)

这个例子不起作用:

text_area = driver.find_element_by_xpath("//div[@id='divtextarea1']").text
#example above ^ doesnt work without .text/.value either
driver.execute_script("arguments[0] = arguments[1]", text_area, my_text)
'''

这应该更正以设置 javascript 层中文本字段的 "value"。

text_area = driver.find_element_by_xpath("//div[@id='divtextarea1']")
# Need to make sure the "value" attribute is set from the JS command
driver.execute_script("arguments[0].value = arguments[1]", text_area, my_text)

参考:https://www.w3schools.com/jsref/prop_textarea_value.asp

我找到了如何复制字符串并将其作为文本粘贴到 Web 中。 下面的示例将字符串值从代码复制到剪贴板,就像使用 ctrl+c

string_variable = "test"
os.system('echo %s| clip' % string_variable) #copy string, like ctrl+c
text_area.send_keys(Keys.CONTROL + "v")      #paste string, like ctrl+v

但我正在寻找其他东西,因为 'echo' 不适用于很长的字符串。 在我的任务中,我不得不将整个 .xml 文件值粘贴到文本区域,我是这样做的,如下所示。

xmlfile = "C:\Users\myfile.xml"
os.system('type "%s" | clip' % xmlfile)      #copy whole file value(string), like ctrl+c
text_area.send_keys(Keys.CONTROL + "v")      #paste string, like ctrl+v