代碼如下:
import time
import ddddocr
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
# 打開google瀏覽器
option = webdriver.ChromeOptions()
option.add_argument(
"--user-data-dir=C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\crawl\\Default") # 瀏覽器存儲用戶配置文件的目錄。
option.add_argument("--profile-directory=Default") # 選擇要與啟動的瀏覽器關(guān)聯(lián)的配置文件目錄
# 反反爬配置
option.add_argument("--disable-blink-features=AutomationControlled") # 禁用blink特征
option.add_experimental_option('excludeSwitches', ['enable-automation'])
# 開始獲取cookie
browser = webdriver.Chrome(options=option)
browser.get("https://adv.aiclk.com/#/index/login~force=1")
time.sleep(10)
# 我們就一個賬戶, 所以在這里寫死用戶名和密碼
user_name = 'user_name'
password = 'password'
try:
browser.find_element(By.XPATH, "http://input[@id='ctrltextusername']").click()
browser.find_element(By.XPATH, "http://input[@id='ctrltextusername']").clear()
browser.find_element(By.XPATH, "http://input[@id='ctrltextusername']").send_keys(user_name)
time.sleep(2)
browser.find_element(By.XPATH, "http://input[@id='ctrltextpassword']").click()
browser.find_element(By.XPATH, "http://input[@id='ctrltextpassword']").clear()
browser.find_element(By.XPATH, "http://input[@id='ctrltextpassword']").send_keys(password)
time.sleep(3)
# 獲取src
code_image = browser.find_element(By.XPATH, "http://img[@id='code_image']")
url = code_image.get_attribute('src')
# 下載
r = requests.get(url)
# 識別驗(yàn)證碼
ocr = ddddocr.DdddOcr()
res = ocr.classification(r.content)
print(res)
browser.find_element(By.XPATH, "http://input[@id='ctrltextcode']").send_keys(res)
browser.find_element(By.XPATH, "http://div[@id='ctrlbuttonsubmit']").click()
time.sleep(10)
cookie = ""
for item in browser.get_cookies():
cookie += item["name"] + "=" + item["value"] + ";"
print(cookie)
# 把拿到的cookie放在txt里, 之后爬取數(shù)據(jù)先拿這里的cookie, 如果過期了再來重新獲取
with open('C:\\Users\\Administrator\\Desktop\\quick_report_crawl\\xxx.txt', 'w') as f:
f.write(cookie)
except Exception as e:
print('廣點(diǎn)通用戶登錄失敗, 失敗原因是: ', e)
# 至此cookie就拿到啦, 后面就是正常的業(yè)務(wù)代碼
一點(diǎn)說明:
安利個巨好用的識別驗(yàn)證碼的庫<ddddocr> gitHub:https://github.com/sml2h3/ddddocr
可能會在版本上遇到問題,我的報(bào)錯參考這篇文檔解決:https://blog.csdn.net/zhuchengchengct/article/details/124854199
我用的版本作為參考:python是3.9.13,ddddocr是1.4.2文章來源:http://www.zghlxwxcb.cn/news/detail-589239.html
如有問題,歡迎大家批評指正~~文章來源地址http://www.zghlxwxcb.cn/news/detail-589239.html
到了這里,關(guān)于爬蟲筆記--Selenium實(shí)現(xiàn)有驗(yàn)證碼網(wǎng)站模擬登錄的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!