python爬蟲登陸網頁版騰訊課堂


 根據騰訊課堂網頁登陸問題進行解說(需要安裝谷歌瀏覽器):

1、導入庫

import requests from selenium import webdriver

2、根據騰訊課堂鏈接,進入頁面,獲取頁面中登陸的xpath,並進行點擊操作。

  獲取xpath的方法是:在如上所示箭頭所指登陸位置右擊操作,點擊檢查,獲取以下頁面。在登陸所在標簽處右擊進行復制xpath。

driver = webdriver.Chrome() driver.get("https://ke.qq.com/course/403521") driver.find_element_by_xpath('//*[@id="js_login"]').click()

3、進入登陸頁面之后獲取登陸方式,本次選擇使用qq進行登陸,獲取qq登陸的xpath並進行點擊操作。

driver.find_element_by_xpath('/html/body/div[4]/div/div[2]/div[2]/a[1]').click()

4、點擊使用賬號密碼登陸。在該登陸過程中出現以下錯誤。

  主要原因是無法找到我們定位的xpath,需要先找到定位元素所處的frame,並從frame中尋找該元素。

 

 

driver.switch_to_frame("login_frame_qq")//引號中添加frame標簽中的name或id值 driver.find_element_by_xpath('//*[@id="switcher_plogin"]').click()

5、獲取到輸入賬號密碼以及登陸位置的xpath。當運行時再次出現定位不到xpath的情況,使用第四步的方法依舊沒能成功,提示所在框架不對,估計是跟第4步的frame標簽的name相同的原因吧。最后的解決方法是:先回到最外層框架,之后進入要定位元素的框架,最后對賬號密碼進行定位。

 

driver.switch_to.default_content()//回到最外層框架 driver.switch_to_frame("login_frame_qq")//進入定位元素的框架 driver.find_element_by_xpath('//*[@id="u"]').clear() driver.find_element_by_xpath('//*[@id="u"]').send_keys("輸入自己的賬號") driver.find_element_by_xpath('//*[@id="p"]').clear() driver.find_element_by_xpath('//*[@id="p"]').send_keys("輸入自己的密碼")

6、點擊登陸按鈕,至此就已經進入網頁版的騰訊課堂了。

driver.find_element_by_xpath('//*[@id="login_button"]').click()

 完整代碼如下:

import requests from selenium import webdriver driver = webdriver.Chrome() driver.get("https://ke.qq.com/course/403521") driver.find_element_by_xpath('//*[@id="js_login"]').click()
time.sleep(5)//等待響應 driver.find_element_by_xpath(
'/html/body/div[4]/div/div[2]/div[2]/a[1]').click() time.sleep(2)
driver.switch_to_frame("login_frame_qq")//引號中添加frame標簽中的name或id值
driver.find_element_by_xpath('//*[@id="switcher_plogin"]').click()
time.sleep(2)
driver.switch_to.default_content()//回到最外層框架
driver.switch_to_frame("login_frame_qq")//進入定位元素的框架
driver.find_element_by_xpath('//*[@id="u"]').clear()
driver.find_element_by_xpath('//*[@id="u"]').send_keys("輸入自己的賬號")
driver.find_element_by_xpath('//*[@id="p"]').clear()
driver.find_element_by_xpath('//*[@id="p"]').send_keys("輸入自己的密碼")
driver.find_element_by_xpath('//*[@id="login_button"]').click()

 本次實驗使用的是Jupyter進行的分段操作,如果合並代碼進行實驗應改變sleep時間,確保頁面已經更新。如有問題,歡迎批評指正,謝謝。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM