最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

如何用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)文章

  • Jupyter Notebook添加代碼自動(dòng)補(bǔ)全功能的實(shí)現(xiàn)

    Jupyter Notebook添加代碼自動(dòng)補(bǔ)全功能的實(shí)現(xiàn)

    這篇文章主要介紹了Jupyter Notebook添加代碼自動(dòng)補(bǔ)全功能的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • Python深度學(xué)習(xí)pytorch神經(jīng)網(wǎng)絡(luò)填充和步幅的理解

    Python深度學(xué)習(xí)pytorch神經(jīng)網(wǎng)絡(luò)填充和步幅的理解

    這篇文章主要介紹了Python深度學(xué)習(xí)pytorch神經(jīng)網(wǎng)絡(luò)填充和步幅的理解
    2021-10-10
  • Python torch.flatten()函數(shù)案例詳解

    Python torch.flatten()函數(shù)案例詳解

    這篇文章主要介紹了Python torch.flatten()函數(shù)案例詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • 基于Python開(kāi)發(fā)一個(gè)文件快速搜索工具

    基于Python開(kāi)發(fā)一個(gè)文件快速搜索工具

    這篇文章主要為大家詳細(xì)介紹了如何基于Python開(kāi)發(fā)一個(gè)文件快速搜索工具,可以實(shí)現(xiàn)多條件文件搜索并實(shí)時(shí)搜索狀態(tài)反饋,需要的可以參考一下
    2025-03-03
  • 解決Tensorflow 使用時(shí)cpu編譯不支持警告的問(wèn)題

    解決Tensorflow 使用時(shí)cpu編譯不支持警告的問(wèn)題

    今天小編就為大家分享一篇解決Tensorflow 使用時(shí)cpu編譯不支持警告的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-02-02
  • Django中使用celery完成異步任務(wù)的示例代碼

    Django中使用celery完成異步任務(wù)的示例代碼

    本篇文章主要介紹了Django中使用celery完成異步任務(wù)的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-01-01
  • Python 如何實(shí)現(xiàn)文件自動(dòng)去重

    Python 如何實(shí)現(xiàn)文件自動(dòng)去重

    這篇文章主要介紹了Python 實(shí)現(xiàn)文件自動(dòng)去重操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • python常見(jiàn)的格式化輸出小結(jié)

    python常見(jiàn)的格式化輸出小結(jié)

    今天在寫(xiě)代碼的時(shí)候,需要統(tǒng)一化輸出格式進(jìn)行,一時(shí)想不起竟具體細(xì)節(jié),用了最笨的方法,所以覺(jué)得有必要將常見(jiàn)的方法進(jìn)行一個(gè)總結(jié)。下面這篇文中就給大家總結(jié)了python中常見(jiàn)的格式化輸出,比如打印字符串、打印整數(shù)和打印浮點(diǎn)數(shù)等,下面來(lái)看看詳細(xì)的輸出方法吧。
    2016-12-12
  • Python?flask使用ajax上傳文件的示例代碼

    Python?flask使用ajax上傳文件的示例代碼

    這篇文章主要介紹了Python?flask使用ajax上傳文件,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-07-07
  • 關(guān)于pyqt5彈出提示框的詳細(xì)介紹

    關(guān)于pyqt5彈出提示框的詳細(xì)介紹

    在實(shí)際的程序開(kāi)發(fā)中經(jīng)常會(huì)用到各種各樣的消息框來(lái)給用戶一些提示或提醒,下面這篇文章主要給大家介紹了關(guān)于pyqt5彈出提示框的詳細(xì)介紹,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-08-08

最新評(píng)論

和龙市| 甘谷县| 长沙市| 阿尔山市| 西乌珠穆沁旗| 扎赉特旗| 舟曲县| 稻城县| 海南省| 云阳县| 华坪县| 定边县| 绥江县| 榆林市| 康定县| 太和县| 东光县| 碌曲县| 新蔡县| 大渡口区| 博罗县| 三河市| 长武县| 广州市| 阳城县| 南漳县| 茌平县| 同江市| 蒲江县| 林周县| 揭阳市| 时尚| 固镇县| 高唐县| 宽城| 武冈市| 阿勒泰市| 霍邱县| 古蔺县| 历史| 呼图壁县|