一、軟體準備
1。 安裝Python 環境
2。 安裝selenium庫 pip install selenium
3。 下載chromedriver 複製到 C:\Windows\System32
http://npm。taobao。org/mirrors/chromedriver/ 選擇對應的chrome版本。
二、實現方法
l 使用 Selenium 工具自動化模擬瀏覽器,當前重點是瞭解對元素的定位
如果我們想定位一個元素,可以透過 id、name、class、tag、連結上的全部文字、連結上的部分文字、XPath 或者 CSS 進行定位,在 Selenium Webdriver 中也提供了這 8 種方法方便我們定位元素。
1。 透過 id 定位:我們可以使用 find_element_by_id() 函式。比如我們想定位 id=loginName 的元素,就可以使用browser。find_element_by_id(“loginName”)。
2。 透過 name 定位:我們可以使用 find_element_by_name() 函式,比如我們想要對 name=key_word 的元素進行定位,就可以使用 browser。find_element_by_name(“key_word”)。
3。 透過 class 定位:可以使用 find_element_by_class_name() 函式。
4。 透過 tag 定位:使用 find_element_by_tag_name() 函式。
5。 透過 link 上的完整文字定位:使用 find_element_by_link_text() 函式。
6。 透過 link 上的部分文字定位:使用 find_element_by_partial_link_text() 函式。有時候超連結上的文字很長,我們透過查詢部分文字內容就可以定位。
7。 透過 XPath 定位:使用 find_element_by_xpath() 函式。使用 XPath 定位的通用性比較好,因為當 id、name、class 為多個,或者元素沒有這些屬性值的時候,XPath 定位可以幫我們完成任務。
8。 透過 CSS 定位:使用 find_element_by_css_selector() 函式。CSS 定位也是常用的定位方法,相比於 XPath 來說更簡潔。
對元素進行的操作包括:
1。 清空輸入框的內容:使用 clear() 函式;
2。 在輸入框中輸入內容:使用 send_keys(content) 函式傳入要輸入的文字;
3。 點選按鈕:使用 click() 函式,如果元素是個按鈕或者連結的時候,可以點選操作;
4。 提交表單:使用 submit() 函式,元素物件為一個表單的時候,可以提交表單;
l 注意:由於selenium開啟的chrome是原始設定的,所以訪問微博首頁時一定會彈出來是否提示訊息的彈窗,導致不能定位到輸入框。可使用如下方法關閉彈窗:
prefs = {“profile。default_content_setting_values。notifications”: 2}
l 如何定位元素
需要定位的元素,點選檢查。
另外:可以下載 XPath Helper外掛,安裝後 在網頁上選取想要提取的元素, 點選右鍵 選中 檢查 然後 開發者工具自動開啟 你可以看到 HTML程式碼 ,選中然後再次點選右鍵,選中copy 裡的 copy to xpath這樣就得到了xpath的值了。
三、完整程式碼
from selenium import webdriver
import time
# 登入微博併發布文字微博
def weibo_loginandPublish(username, password,content):
chrome_options = webdriver。ChromeOptions()
# 把允許提示這個彈窗關閉
prefs = {“profile。default_content_setting_values。notifications”: 2}
chrome_options。add_experimental_option(“prefs”, prefs)
driver = webdriver。Chrome(options=chrome_options)
driver。get(‘http://weibo。com/’)
time。sleep(5)
input_account=driver。find_element_by_id(‘loginname’)
input_psw=driver。find_element_by_css_selector(‘input[type=“password”]’)
# 輸入使用者名稱和密碼
input_account。send_keys(username)
input_psw。send_keys(password)
# 找到登入按鈕
bt_logoin=driver。find_element_by_xpath(‘//div[@node-type=“normal_form”]//div[@class=“ info_list login_btn”]/a’) # 找到登入按鈕
bt_logoin。click() # 點選登入
# 等待頁面載入完畢
time。sleep(5)
driver。get(‘https://weibo。com’)
driver。implicitly_wait(5)
# 點選右上角的釋出按鈕
post_button = driver。find_element_by_css_selector(“[node-type=‘publish’]”)。click()
# 在彈出的文字框中輸入內容
content_textarea = driver。find_element_by_css_selector(“textarea。W_input”)。send_keys(content)
time。sleep(2)
# 點擊發布按鈕
post_button = driver。find_element_by_css_selector(“[node-type=‘submit’]”)。click()
time。sleep(1)
if __name__==“__main__”:
# 設定使用者名稱、密碼
username = ‘xxxxx’
password = “xxxxx”
content = ‘每天進步一點’
weibo_loginandPublish(username, password,content)
自動登入微博併發布訊息