Selenium2+python自動化24-js處理富文本(帶iframe)

來源:互聯網
上載者:User

標籤:路徑   中文   隨筆   body   height   click   ima   end   編輯框   

前言

    上一篇Selenium2+python自動化23-富文本(自動發帖)解決了富文本上iframe問題,其實沒什麼特別之處,主要是iframe的切換,本篇講解通過js的方法處理富文本上iframe的問題

一、載入配置

    1.開啟部落格園寫隨筆,首先需要登入,這裡為了避免透露個人賬戶資訊,我直接載入設定檔,免登入了。

      不懂如何載入設定檔的,看這篇Selenium2+python自動化18-載入Firefox配置

二、開啟編輯介面

    1.部落格首頁地址:bolgurl = "http://www.cnblogs.com/"

    2.我的部落格園地址:yoyobolg = bolgurl + "yoyoketang"

    3.點擊“新隨筆”按鈕,id=blog_nav_newpost

三、定位iframe

    1.開啟編輯介面後先不要急著輸入內容,先sleep幾秒鐘

    2.輸入標題,這裡直接通過id就可以定位到,沒什麼痛點

    3.接下來就是重點要講的富文本的編輯,這裡編輯框有個iframe,所以需要先切換

(關於iframe不懂的可以看前面這篇:Selenium2+python自動化14-iframe)

 

 四、js輸入中文

    1.這裡定位編輯本文是定位的紅色框框位置body部分,也就是id=tinymce

    2.定位到之後,用js的方法直接輸入,無需切換iframe

    3.直接點儲存按鈕,無需再切回來

 

五、參考代碼:

# coding:utf-8
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

# profileDir路徑對應直接電腦的配置路徑
profileDir = r‘C:\xxx\xxx\AppData\Roaming\Mozilla\Firefox\Profiles\1x41j9of.default‘
profile = webdriver.FirefoxProfile(profileDir)
driver = webdriver.Firefox(profile)

bolgurl = "http://www.cnblogs.com/"
yoyobolg = bolgurl + "yoyoketang"
driver.get(yoyobolg)
driver.find_element_by_id("blog_nav_newpost").click()

time.sleep(5)
edittile = u"Selenium2+python自動化23-富文本"
editbody = u"這裡是發帖的本文"
driver.find_element_by_id("Editor_Edit_txbTitle").send_keys(edittile)


body = "這裡是通過js發的本文內容"

# js處理iframe問題(js代碼太長了,我分成兩行了)
js = ‘document.getElementById("Editor_Edit_EditorBody_ifr")‘ \
     ‘.contentWindow.document.body.innerHTML="%s"‘ % body
driver.execute_script(js)
# 儲存草稿
driver.find_element_by_id("Editor_Edit_lkbDraft").click()

Selenium2+python自動化24-js處理富文本(帶iframe)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.