亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

如何用Python實(shí)現(xiàn)自動(dòng)發(fā)送微博

 更新時(shí)間:2022年01月23日 14:16:02   作者:簡(jiǎn)說(shuō)Python  
大家好,本篇文章主要講的是如何用Python實(shí)現(xiàn)自動(dòng)發(fā)送微博,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏

一、軟件準(zhǔn)備

1.安裝Python 環(huán)境

首先需要你的電腦安裝好了Python環(huán)境,并且安裝好了Python開(kāi)發(fā)工具。如果你還沒(méi)有安裝,可以參考以下文章:如果僅用Python來(lái)處理數(shù)據(jù)、爬蟲(chóng)、數(shù)據(jù)分析或者自動(dòng)化腳本、機(jī)器學(xué)習(xí)等,建議使用Python基礎(chǔ)環(huán)境+jupyter即可,安裝使用參考??Windows/Mac 安裝、使用Python環(huán)境+jupyter notebook??

2.安裝selenium庫(kù)

pip install selenium

3.下載谷歌瀏覽器驅(qū)動(dòng)chromedriver,下載地址:http://npm.taobao.org/mirrors/chromedriver/需要選擇對(duì)應(yīng)的谷歌瀏覽器版本,(谷歌瀏覽器訪問(wèn):chrome://settings/help,即可查看版本)

如何用 Python 自動(dòng)發(fā)送微博?_python

下載好后,隨便發(fā)到一個(gè)路徑下即可(簡(jiǎn)單點(diǎn)最好,記住路徑)。

二、實(shí)現(xiàn)方法

2.1 使用 Selenium 工具自動(dòng)化模擬瀏覽器,當(dāng)前重點(diǎn)是了解對(duì)元素的定位

我們想定位一個(gè)元素,可以通過(guò) id、name、class、tag、鏈接上的全部文本、鏈接上的部分文本、XPath 或者 CSS 進(jìn)行定位,在 Selenium Webdriver 中也提供了這 8 種方法方便我們定位元素。

1)通過(guò) id 定位:我們可以使用 find_element_by_id() 函數(shù)。比如我們想定位 id=loginName 的元素,就可以使用browser.find_element_by_id(“loginName”)。

2)通過(guò) name 定位:我們可以使用 find_element_by_name() 函數(shù),比如我們想要對(duì) name=key_word 的元素進(jìn)行定位,就可以使用 browser.find_element_by_name(“key_word”)。

3)通過(guò) class 定位:可以使用 find_element_by_class_name() 函數(shù)。

4)通過(guò) tag 定位:使用 find_element_by_tag_name() 函數(shù)。

5)通過(guò) link 上的完整文本定位:使用 find_element_by_link_text() 函數(shù)。

6)通過(guò) link 上的部分文本定位:使用 find_element_by_partial_link_text() 函數(shù)。有時(shí)候超鏈接上的文本很長(zhǎng),我們通過(guò)查找部分文本內(nèi)容就可以定位。

7)通過(guò) XPath 定位:使用 find_element_by_xpath() 函數(shù)。使用 XPath 定位的通用性比較好,因?yàn)楫?dāng) id、name、class 為多個(gè),或者元素沒(méi)有這些屬性值的時(shí)候,XPath 定位可以幫我們完成任務(wù)。

8)通過(guò) CSS 定位:使用 find_element_by_css_selector() 函數(shù)。CSS 定位也是常用的定位方法,相比于 XPath 來(lái)說(shuō)更簡(jiǎn)潔。

2.2 對(duì)元素進(jìn)行的操作包括

1)清空輸入框的內(nèi)容:使用 clear() 函數(shù);

2)在輸入框中輸入內(nèi)容:使用 send_keys(content) 函數(shù)傳入要輸入的文本;

3)點(diǎn)擊按鈕:使用 click() 函數(shù),如果元素是個(gè)按鈕或者鏈接的時(shí)候,可以點(diǎn)擊操作;

4)提交表單:使用 submit() 函數(shù),元素對(duì)象為一個(gè)表單的時(shí)候,可以提交表單;

2.3 注意

由于selenium打開(kāi)的chrome是原始設(shè)置的,所以訪問(wèn)微博首頁(yè)時(shí)一定會(huì)彈出來(lái)是否提示消息的彈窗,導(dǎo)致不能定位到輸入框??墒褂萌缦路椒P(guān)閉彈窗:

prefs = {"profile.default_content_setting_values.notifications": 2}

2.4 如何定位元素

點(diǎn)擊需要定位的元素,然后右鍵選擇檢查,可以調(diào)出谷歌開(kāi)發(fā)者工具。

如何用 Python 自動(dòng)發(fā)送微博?_python_02

獲取xpath 路徑,點(diǎn)擊谷歌開(kāi)發(fā)者工具左上角的小鍵頭(選擇元素),選擇自己要查看的地方的,開(kāi)發(fā)者工具就會(huì)自動(dòng)定位到對(duì)應(yīng)元素的源碼位置,選中對(duì)應(yīng)源碼,然后右鍵,選擇??Copy??-> ??Copy XPath??即可獲取到xpath 路徑。

如何用 Python 自動(dòng)發(fā)送微博?_python_03

另外: 可以下載 XPath Helper插件,安裝后 在網(wǎng)頁(yè)上選取想要提取的元素, 點(diǎn)擊右鍵 選中 檢查 然后 開(kāi)發(fā)者工具自動(dòng)打開(kāi) 你可以看到 HTML代碼 ,選中然后再次點(diǎn)擊右鍵,選中copy 里的 copy to xpath這樣就得到了xpath的值了。

三、完整代碼

實(shí)現(xiàn)思路: 其實(shí)和平時(shí)我們正常操作一樣,只不過(guò)這里,全程由selenium來(lái)實(shí)現(xiàn),模擬點(diǎn)擊和輸入,所以整個(gè)過(guò)程為:打開(kāi)登錄頁(yè)面->輸入賬號(hào)密碼->點(diǎn)擊登錄按鈕->在發(fā)微博框輸入發(fā)送內(nèi)容->點(diǎn)擊發(fā)送按鈕->關(guān)閉瀏覽器(自選)。

3.1 目前自動(dòng)輸入賬號(hào)可能會(huì)彈出登錄保護(hù)需掃二維碼驗(yàn)證

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time


'''
自動(dòng)發(fā)布微博
content:發(fā)送內(nèi)容
username:微博賬號(hào)
password:微博密碼
'''
def post_weibo(content, username, password):
    # 加載谷歌瀏覽器驅(qū)動(dòng)
    path = r'C:/MyEnv/chromedriver.exe '  # 指定驅(qū)動(dòng)存放目錄
    ser = Service(path)
    chrome_options = webdriver.ChromeOptions()
    # 把允許提示這個(gè)彈窗關(guān)閉
    prefs = {"profile.default_content_setting_values.notifications": 2}
    chrome_options.add_experimental_option("prefs", prefs)
    driver = webdriver.Chrome(service=ser, options=chrome_options)
    driver.maximize_window()  # 設(shè)置頁(yè)面最大化,避免元素被隱藏  
    
    print('# get打開(kāi)微博主頁(yè)')
    url = 'http://weibo.com/login.php'
    driver.get(url)  # get打開(kāi)微博主頁(yè)
    time.sleep(5)  # 頁(yè)面加載完全
    
    print('找到用戶名 密碼輸入框')
    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)
    
    print('# 找到登錄按鈕 //div[@node-type="normal_form"]//div[@]/a')
    bt_logoin = driver.find_element_by_xpath('//div[@node-type="normal_form"]//div[@]/a')  # 找到登錄按鈕
    bt_logoin.click()  # 點(diǎn)擊登錄
    # 等待頁(yè)面加載完畢  #有的可能需要登錄保護(hù),需掃碼確認(rèn)下
    time.sleep(40)

    # 登錄后 默認(rèn)到首頁(yè),有微博發(fā)送框
    print('# 找到文本輸入框 輸入內(nèi)容 //*[@id="homeWrap"]/div[1]/div/div[1]/div/textarea')
    weibo_content = driver.find_element_by_xpath('//*[@id="homeWrap"]/div[1]/div/div[1]/div/textarea')
    weibo_content.send_keys(content)
    print('# 點(diǎn)擊發(fā)送按鈕 //*[@id="homeWrap"]/div[1]/div/div[4]/div/button')
    bt_push = driver.find_element_by_xpath('//*[@id="homeWrap"]/div[1]/div/div[4]/div/button')
    bt_push.click()  # 點(diǎn)擊發(fā)布
    time.sleep(15)
    
    driver.close()  # 關(guān)閉瀏覽器

if __name__ == '__main__':
    username = '微博用戶名'
    password = "微博密碼"
    # 自動(dòng)發(fā)微博
    content = '每天進(jìn)步一點(diǎn)'
    post_weibo(content, username, password)

如何用 Python 自動(dòng)發(fā)送微博?_selenium_04

通過(guò)cookie進(jìn)行登錄可跳過(guò)掃碼登錄,cookie過(guò)期后重新獲取下cookie就可以了。

導(dǎo)入第三方包

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time
import requests
import json

獲取cookie到本地

這里主要利用了selenium的get_cookies函數(shù)獲取cookies。

# 獲取cookies 到本地
def get_cookies(driver):
    driver.get('https://weibo.com/login.php')
    time.sleep(20) # 留時(shí)間進(jìn)行掃碼
    Cookies = driver.get_cookies() # 獲取list的cookies
    jsCookies = json.dumps(Cookies) # 轉(zhuǎn)換成字符串保存
    with open('cookies.txt', 'w') as f:
        f.write(jsCookies)
    print('cookies已重新寫(xiě)入!')
    

# 讀取本地的cookies
def read_cookies():
    with open('cookies.txt', 'r', encoding='utf8') as f:
        Cookies = json.loads(f.read())
    cookies = []
    for cookie in Cookies:
        cookie_dict = {
            'domain': '.weibo.com',
            'name': cookie.get('name'),
            'value': cookie.get('value'),
            'expires': '',
            'path': '/',
            'httpOnly': False,
            'HostOnly': False,
            'Secure': False
        }
        cookies.append(cookie_dict)
    return cookies

利用cookie登錄微博并發(fā)送文字 完整代碼

# 初始化瀏覽器 打開(kāi)微博登錄頁(yè)面
def init_browser():
    path = r'C:/MyEnv/chromedriver.exe '  # 指定驅(qū)動(dòng)存放目錄
    ser = Service(path)
    chrome_options = webdriver.ChromeOptions()
    # 把允許提示這個(gè)彈窗關(guān)閉
    prefs = {"profile.default_content_setting_values.notifications": 2}
    chrome_options.add_experimental_option("prefs", prefs)
    driver = webdriver.Chrome(service=ser, options=chrome_options)
    driver.maximize_window()    
    driver.get('https://weibo.com/login.php')
    return driver
    
    
# 讀取cookies 登錄微博
def login_weibo(driver):
    cookies = read_cookies()
    for cookie in cookies:
        driver.add_cookie(cookie)
    time.sleep(3)
    driver.refresh()  # 刷新網(wǎng)頁(yè)

# 發(fā)布微博
def post_weibo(content, driver):
    time.sleep(5)
    weibo_content = driver.find_element_by_xpath('//*[ @id ="homeWrap"]/div[1]/div/div[1]/div/textarea')
    weibo_content.send_keys(content)
    bt_push = driver.find_element_by_xpath('//*[@id="homeWrap"]/div[1]/div/div[4]/div/button')
    bt_push.click()  # 點(diǎn)擊發(fā)布
    time.sleep(5)
    driver.close()  # 關(guān)閉瀏覽器

    
if __name__ == '__main__':
    # cookie登錄微博
    driver = init_browser()
    login_weibo(driver)
    # 自動(dòng)發(fā)微博
    content = '今天的天氣真不錯(cuò)~'
    post_weibo(content, driver)

如何用 Python 自動(dòng)發(fā)送微博?_python_05

拓展:檢測(cè)cookies有效性

檢測(cè)方法:利用本地cookies向微博發(fā)送get請(qǐng)求,如果返回的頁(yè)面源碼中包含自己的微博昵稱,就說(shuō)明cookies還有效,否則無(wú)效。

如何用 Python 自動(dòng)發(fā)送微博?_自動(dòng)化實(shí)戰(zhàn)_06

# 檢測(cè)cookies的有效性
def check_cookies():
    # 讀取本地cookies
    cookies = read_cookies()
    s = requests.Session()
    for cookie in cookies:
        s.cookies.set(cookie['name'], cookie['value'])
    response = s.get("https://weibo.com")
    html_t = response.text
    # 檢測(cè)頁(yè)面是否包含我的微博用戶名
    if '老表max' in html_t:
        return True
    else:
        return False

拓展:定時(shí)每日自動(dòng)發(fā)送

from apscheduler.schedulers.blocking import BlockingSchedulera

'''
每天早上9:00 發(fā)送一條微博
'''
def every_day_nine():
    # cookie登錄微博
    driver = init_browser()
    login_weibo(driver)
    req = requests.get('https://hitokoto.open.beeapi.cn/random')
    get_sentence = req.json()
    content =  f'【每日一言】{get_sentence["data"]} 來(lái)自:一言api'
    # 自動(dòng)發(fā)微博
    post_weibo(content, driver)
    

    
# 選擇BlockingScheduler調(diào)度器
sched = BlockingScheduler(timezone='Asia/Shanghai')

# job_every_nine 每天早上9點(diǎn)運(yùn)行一次  日常發(fā)送
sched.add_job(every_day_nine, 'cron', hour=9)

# 啟動(dòng)定時(shí)任務(wù)
sched.start()

總結(jié)

到此這篇關(guān)于如何用Python實(shí)現(xiàn)自動(dòng)發(fā)送微博的文章就介紹到這了,更多相關(guān)Python發(fā)送微博內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python 輸出列表元素實(shí)例(以空格/逗號(hào)為分隔符)

    python 輸出列表元素實(shí)例(以空格/逗號(hào)為分隔符)

    今天小編就為大家分享一篇python 輸出列表元素實(shí)例(以空格/逗號(hào)為分隔符),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-12-12
  • Python 圖像處理之PIL庫(kù)詳解用法

    Python 圖像處理之PIL庫(kù)詳解用法

    對(duì)于圖像識(shí)別,大量的工作在于圖像的處理,處理效果好,那么才能很好地識(shí)別,因此,良好的圖像處理是識(shí)別的基礎(chǔ)。在Python中,有一個(gè)優(yōu)秀的圖像處理框架,就是PIL庫(kù),本文會(huì)介紹PIL庫(kù)中的各種方法,并列舉相關(guān)例子
    2021-11-11
  • Pycharm 如何連接遠(yuǎn)程服務(wù)器并debug調(diào)試

    Pycharm 如何連接遠(yuǎn)程服務(wù)器并debug調(diào)試

    本文主要介紹了Pycharm 如何連接遠(yuǎn)程服務(wù)器并debug調(diào)試,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • PyQt 圖解Qt Designer工具的使用方法

    PyQt 圖解Qt Designer工具的使用方法

    這篇文章主要介紹了PyQt 圖解Qt Designer工具的使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • python在windows下實(shí)現(xiàn)ping操作并接收返回信息的方法

    python在windows下實(shí)現(xiàn)ping操作并接收返回信息的方法

    這篇文章主要介紹了python在windows下實(shí)現(xiàn)ping操作并接收返回信息的方法,實(shí)例分析了Python實(shí)現(xiàn)ping操作的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-03-03
  • python讀取txt文件并取其某一列數(shù)據(jù)的示例

    python讀取txt文件并取其某一列數(shù)據(jù)的示例

    今天小編就為大家分享一篇python讀取txt文件并取其某一列數(shù)據(jù)的示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-02-02
  • 淺析python中特殊文件和特殊函數(shù)

    淺析python中特殊文件和特殊函數(shù)

    這篇文章主要介紹了python中特殊文件和特殊函數(shù)的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-02-02
  • 快速解決jupyter啟動(dòng)卡死的問(wèn)題

    快速解決jupyter啟動(dòng)卡死的問(wèn)題

    這篇文章主要介紹了快速解決jupyter啟動(dòng)卡死的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-04-04
  • Python使用爬蟲(chóng)猜密碼

    Python使用爬蟲(chóng)猜密碼

    我們可以通過(guò)python 來(lái)實(shí)現(xiàn)這樣一個(gè)簡(jiǎn)單的爬蟲(chóng)猜密碼功能。下面就看看如何使用python來(lái)實(shí)現(xiàn)這樣一個(gè)功能,對(duì)python爬蟲(chóng)猜密碼相關(guān)知識(shí)感興趣的朋友參考下吧
    2016-02-02
  • Python鏈?zhǔn)秸{(diào)用數(shù)據(jù)處理實(shí)際應(yīng)用實(shí)例探究

    Python鏈?zhǔn)秸{(diào)用數(shù)據(jù)處理實(shí)際應(yīng)用實(shí)例探究

    本文將深入介紹Python鏈?zhǔn)秸{(diào)用的概念、原理以及實(shí)際應(yīng)用,通過(guò)豐富的示例代碼,幫助讀者更全面地理解和應(yīng)用這一編程技巧
    2024-01-01

最新評(píng)論