python - 如何使用 python webdriver 在 html 标签之间放置文本

标签 python html python-2.7 python-3.x selenium-webdriver

如何使用 python WebDriver 在 html 标签之间放置文本?

<!--html cod-->
<span class="py"></span>  
<!--I want to put text between span tag with python WebDriver like this-->
<span class="py">text</span>

最佳答案

您可以在要添加文本之前使用 selenium 获取元素,然后使用 javascript 在该元素末尾后立即插入文本。

例如:

node = driver.find_element_by_xpath("//span[@class='py']")
script = "arguments[0].insertAdjacentHTML('afterEnd', arguments[1])"
driver.execute_script(script, node, "the new text")

这是一个完整的工作示例,假设该网站至少有一个 div(在我撰写本文时确实如此):

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.example.com")

node = driver.find_element_by_xpath("/html/body/div")
script = "arguments[0].insertAdjacentHTML('afterEnd', arguments[1])"
driver.execute_script(script, node, "the new text")

关于python - 如何使用 python webdriver 在 html 标签之间放置文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37485974/

相关文章:

python - 验证字节流是否为有效的 UTF-8(或其他编码),无需复制

javascript - 带有多个按钮和 div 的 Bootstrap Collapse

python-2.7 - Python 运行系统命令并保存输出

python - 发出请求时,x-auth-token 未在 header 中传递

python - 大型平面平行板电容器内的简单摆

python请求json返回单引号

html - H2 和段落,内联?

javascript - 单击 Bootstrap 链接内的插入符号图标不起作用

python - 在 pandas df 中按顺序排列值

python - 如何使用原始输入来定义变量