目錄
頁面分析
引入selenium模塊及驅動
1、并將安裝好的Chromedriver.exe引入到代碼中
2、瀏覽器驅動引入
爬蟲模擬登錄
1、設定網址鏈接
2、切換到賬號密碼登錄
3、找到用戶名密碼的控制元件ID
4、注入用戶名和密碼
5、模擬登錄點擊
成功登錄CSDN
先上效果
頁面分析
CSDN登錄頁面如下圖

引入selenium模塊及驅動
1、并將安裝好的Chromedriver.exe引入到代碼中
# -*- coding:utf-8 -*-
from selenium import webdriver
import os
import time
#引入chromedriver.exe
chromedriver="C:/Users/lex/AppData/Local/Google/Chrome/Application/chromedriver.exe"
os.environ["webdriver.chrome.driver"] = chromedriver
browser = webdriver.Chrome(chromedriver)
2、瀏覽器驅動引入
驅動下載地址:
https://download.csdn.net/download/weixin_42350212/14983610
將驅動下載后,復制chromedriver.exe 到谷歌瀏覽器的安裝路徑下,與Chrome.exe啟動檔案并列的目錄下:

爬蟲模擬登錄
1、設定網址鏈接
#設定瀏覽器需要打開的url
url = "https://passport.csdn.net/login?code=public"
browser.get(url)
2、切換到賬號密碼登錄
使用selenium模擬點擊 賬號密碼登錄的選項
#使用selenium選擇 賬號登錄按鈕
browser.find_element_by_link_text("賬號密碼登錄").click()
3、找到用戶名密碼的控制元件ID

4、注入用戶名和密碼
根據頁面代碼分析,獲得用戶名的id屬性為all,密碼的id屬性為password-number
使用python代碼,注入用戶名密碼
browser.find_element_by_id("all").clear()
browser.find_element_by_id("all").send_keys("xxxx@gmail.com")
time.sleep(2)
browser.find_element_by_id("password-number").clear()
browser.find_element_by_id("password-number").send_keys("1212121212")

5、模擬登錄點擊
分析頁面結構,模擬點擊登錄按鈕,
分析可獲得,登錄按鈕的class屬性為btn btn-primary,根據class來鎖定該按鈕
time.sleep(1)
#增加一秒鐘的時間間隔
browser.find_element_by_css_selector("[class='btn btn-primary']").click()

成功登錄CSDN

完整代碼
# -*- coding:utf-8 -*-
from selenium import webdriver
import os
import time
from selenium import webdriver # 從selenium匯入webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
import json
import time
#引入chromedriver.exe
chromedriver="C:/Users/lex/AppData/Local/Google/Chrome/Application/chromedriver.exe"
os.environ["webdriver.chrome.driver"] = chromedriver
browser = webdriver.Chrome(chromedriver)
#設定瀏覽器需要打開的url
url = "https://passport.csdn.net/login?code=public"
browser.get(url)
browser.find_element_by_link_text("賬號密碼登錄").click()
browser.find_element_by_id("all").clear()
browser.find_element_by_id("all").send_keys("你的郵箱地址")
time.sleep(1)
browser.find_element_by_id("password-number").clear()
browser.find_element_by_id("password-number").send_keys("你的登錄密碼")
time.sleep(1)
browser.find_element_by_css_selector("[class='btn btn-primary']").click()
歡迎關注公眾號:hacklex 提供各種資源下載,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/278405.html
標籤:AI

