将文本插入非格式对象

时间:2019-07-10 23:44:43

标签: python selenium selenium-webdriver

(这是我有史以来的第一个Selenium脚本和有史以来的第一个堆栈文章,尚不完全清楚如何做到这一点:P)

我正在尝试将变量(数字)插入似乎不是表单对象(而不是主体)的对象中。

使用检查元素进行编辑时,我可以编辑正文的html,它将允许我将编辑后的html作为新的论坛帖子发布。因此,这可能是将变量插入html的潜在方法。

Youtube代码示例: https://www.youtube.com/watch?v=_6VqrMOMBeI

手动编辑正文代码并发布的YouTube示例 https://youtu.be/YrT88IV-obg

网站链接(如果您想看一下) https://camelotkingdom.com

我尝试在堆栈上进行研究,以查看是否可以找到其他人解决此问题的示例。

这是我发现的主线程: Modify innerHTML using Selenium

Python代码:

loginpage = 'http://camelotkingdom.com/login'
# login page for the website (login code redacted)

thread = 'http://camelotkingdom.com/threads/count.22/'
# counting thread link

main_browser = webdriver.Chrome("D:\AutoForum\extras\chromedriver.exe")
# chrome driver variable

# below code collects the latest count number (based on post number)
def getlatestnumber():
    main_browser.get(thread)
    # goes to the thread page

    time.sleep(2)
    # waiting for page to fully load

    links = main_browser.find_elements_by_partial_link_text('#')
    for link in links:
        a = link.get_attribute("text")
        a = a.replace('#', '')
        a = int(a)
    # grabs the current count number

    global currentnum
    currentnum = a + 1
    # sets the next count number

    print("[DEBUG] Next count is:",currentnum)

def post_main():
    print("[DEBUG] Number posting:",currentnum)

    comment = "test"
    # text to enter into the post creator iframe

    editable = main_browser.find_element_by_css_selector("iframe")
    editable.click()
    # finding and clicking the post creator iframe

    element = main_browser.execute_script("var ele=arguments[0]; ele.innerHTML = '<p>" + comment +  "</p>';", editable);
    # editing the iframe code to include the variable in a paragraph tag.



 #main_browser.find_element_by_xpath("/html/body/div[2]/div/div[2]/div/div/div[2]/div[4]/form/div[2]/input[2]").click()

网站正文代码

<body contenteditable="true" dir="LTR" style="overflow-y: hidden; min-height: 99px;"><p><br></p></body>

完整代码: 查看来源:http://camelot.treasuremc.net/threads/count.22/

我希望代码将变量发布到论坛主题中。

1 个答案:

答案 0 :(得分:1)

请您在下面的代码中尝试一下。

 iframe = driver.find_elements_by_tag_name("iframe")[0]
 driver.switch_to.frame(iframe)
 driver.execute_script("document.body.innerHTML = '<p>test</p>'")