每日简单小妙招:使用python自动登录CSDN等各大网站
文章目錄
- 1、代碼演示
- 2、過程詳解
- 2.1、chromedriver.exe驅(qū)動(dòng)下載
- 2.1.1、chromedriver.exe簡(jiǎn)介
- 2.1.2、chromedriver.exe下載地址
- 2.1.3、如何下載對(duì)應(yīng)得版本
- 2.1.4、chromedriver.exe存放位置
- 2.2、selenium詳解
- 2.3、元素對(duì)象獲取
- 2.3.1、定位
- 2.3.2、獲取元素對(duì)象
- 2.4、流程
- 3、總結(jié)
1、代碼演示
from selenium import webdriver import time #去掉自動(dòng)化控制提示 options = webdriver.ChromeOptions() options.add_experimental_option('useAutomationExtension', false) options.add_experimental_option("excludeSwitches", ['enable-automation']) #打開Chrome瀏覽器,參數(shù)是chromedriver.exe驅(qū)動(dòng),下載方式下面會(huì)詳細(xì)說 # r是表名\不做為轉(zhuǎn)義符 driver = webdriver.Chrome(r'C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe') #最大化 driver.maximize_window() #休眠一秒 time.sleep(1) #定位到csdn登錄頁面 driver.get('https://passport.csdn.net/login') time.sleep(1) #通過xpath定位到用戶名密碼登錄位置,點(diǎn)擊進(jìn)行用戶名和密碼的輸入 driver.find_element_by_xpath('//*[@id="app"]/div/div/div[1]/div[2]/div[5]/ul/li[2]/a').click() time.sleep(1)#輸入用戶名和密碼函數(shù),并進(jìn)行登錄操作 def _login_(username, password):input_username = driver.find_element_by_xpath('//*[@id="all"]')#點(diǎn)擊賬戶輸入框input_username.click()# 情況輸入框中的內(nèi)容input_username.clear()# 輸入用戶名input_username.send_keys(username)#通過id獲取元素input_password = driver.find_element_by_id('password-number')time.sleep(1)input_password.send_keys(password)driver.find_element_by_xpath('//*[@id="app"]/div/div/div[1]/div[2]/div[5]/div/div[6]/div/button').click()username = "xxxxxxx" password = "xxxxxxxx" _login_(username, password)2、過程詳解
2.1、chromedriver.exe驅(qū)動(dòng)下載
2.1.1、chromedriver.exe簡(jiǎn)介
chromeDriver.exe工具是Chrome的WebDriver,可以用于自動(dòng)化測(cè)試,可以操作瀏覽器,同時(shí)selenium操作chrome瀏覽器需要有ChromeDriver驅(qū)動(dòng)來協(xié)助
2.1.2、chromedriver.exe下載地址
下載地址:http://chromedriver.storage.googleapis.com/index.html
2.1.3、如何下載對(duì)應(yīng)得版本
2.1.4、chromedriver.exe存放位置
解壓之后,放到Chrome的根目錄下
然后放到python項(xiàng)目的根目錄下
2.2、selenium詳解
Selenium 是一個(gè)用于Web應(yīng)用程序測(cè)試的工具
框架底層使用JavaScript模擬真實(shí)用戶對(duì)瀏覽器進(jìn)行操作。測(cè)試腳本執(zhí)行時(shí),瀏覽器自動(dòng)按照腳本代碼做出點(diǎn)擊,輸入,打開,驗(yàn)證等操作,就像真實(shí)用戶所做的一樣,從終端用戶的角度測(cè)試應(yīng)用程序。
2.3、元素對(duì)象獲取
2.3.1、定位
以百度搜索框?yàn)槔?/p>
右鍵搜索框 -> 檢查,然后就會(huì)看到高亮顯示的代碼,至此定位成功
2.3.2、獲取元素對(duì)象
1、通過id : find_element_by_id(‘id’)
‘id’為id屬性的值
2、通過class : find_element_by_class(‘class’)
’class’為class屬性的值
3、通過xpath : find_element_by_xpath(’’)
右鍵定位的搜索框代碼 -> copy -> copy xpath
2.4、流程
1、打開Chrome瀏覽器
2、跳轉(zhuǎn)到csdn登錄的地址
3、獲取賬號(hào)密碼登錄元素對(duì)象,執(zhí)行點(diǎn)擊操作
4、定位到賬戶輸入框,輸入賬號(hào)
5、定位到密碼輸入框,輸入密碼
6、獲取登錄按鈕元素對(duì)象,并執(zhí)行點(diǎn)擊操作
后續(xù)打包工具使用pyinstaller,不再多說
3、總結(jié)
一些大型網(wǎng)站都有強(qiáng)大的反爬機(jī)制,有時(shí)會(huì)進(jìn)性滑動(dòng)窗口和圖片的驗(yàn)證操作,當(dāng)然利用python也能快速的實(shí)現(xiàn)
欲知后事如何,請(qǐng)看下回分解
未完待續(xù)…
總結(jié)
以上是生活随笔為你收集整理的每日简单小妙招:使用python自动登录CSDN等各大网站的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ⅶ:教你一招利用zookeeper作为服
- 下一篇: websocket python爬虫_p