想用selenium爬取需要掃碼獲得磁鏈的磁鏈網站'https://skrbt025.xyz/',該網站是第一次掃碼獲得磁鏈后之后的操作都不用掃碼就可以獲得磁鏈。
我的思路是用selenium跳轉到掃碼頁面之后,使用time.sleep進行等待,在此期間進行人工掃碼,等待結束后使用‘driver.get_cookies()’獲得不需要掃碼的cookie,在下次使用磁鏈網站'https://skrbt025.xyz/'時用driver.add_cookie(cookie)就可以跳過掃碼直接獲取磁鏈。
但實際操作的結果是即使讀取cookie,下一次用selenium爬取磁鏈網站還是需要掃碼。求大神幫我看看代碼和思路哪里出錯了,多謝提醒和指正
。順便問一下為什么我用隱式等待driver.implicitly_wait(10),有時頁面元素加載出來了卻還需要等頁面完全加載后才能繼續下面操作?
import time
from selenium import webdriver
import json
options = webdriver.ChromeOptions()
options.add_argument('start-maximized')
driver = webdriver.Chrome(chrome_options=options)
driver.implicitly_wait(10)
driver.get('https://skrbt025.xyz/')
# 第二次使用時,使用下面代碼匯入已經保存的cookie
# driver.delete_all_cookies()
# with open('cookies.txt','r') as cookief:
# #使用json讀取cookies 注意讀取的是檔案 所以用load而不是loads
# cookieslist = json.load(cookief)
# for cookie in cookieslist:
# #并不是所有cookie都含有expiry 所以要用dict的get方法來獲取
# if isinstance(cookie.get('expiry'), float):
# cookie['expiry'] = int(cookie['expiry'])
# driver.add_cookie(cookie)
# driver.refresh()
# 第一次搜索,網站會驗證你是否為機器人
driver.find_element_by_xpath('//*[@id="search-form"]/div/input').send_keys('編程')
driver.find_element_by_xpath('//*[@id="search-form"]/div/span/button').click()
driver.find_element_by_xpath('//*[@id="search-form"]/div/input').send_keys('編程')
driver.find_element_by_xpath('//*[@id="search-form"]/div/span/button').click()
target = driver.find_element_by_xpath('/html/body/div/div[5]/div[2]/ul[1]/li[1]/a')
js4 = "arguments[0].scrollIntoView();"
driver.execute_script(js4, target)
target.click()
current_windows = driver.window_handles
driver.switch_to.window(current_windows[-1])
driver.find_element_by_xpath('//*[@id="magnet"]').click() #點擊掃碼鏈接
time.sleep(20) #進行掃碼操作
driver.find_element_by_xpath('//*[@id="search-form"]/div/input').send_keys('編程')
driver.find_element_by_xpath('//*[@id="search-form"]/div/span[2]/button').click()
target = driver.find_element_by_xpath('/html/body/div/div[5]/div[2]/ul[1]/li[1]/a')
js4 = "arguments[0].scrollIntoView();"
driver.execute_script(js4, target)
target.click()
current_windows = driver.window_handles
driver.switch_to.window(current_windows[-1])
# 第一次運行時用下面代碼獲取已掃碼后的cookie
# with open('cookies.txt','w') as cookief:
# #將cookies保存為json格式
# cookief.write(json.dumps(driver.get_cookies()))
time.sleep(10)
driver.quit()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/191134.html
上一篇:全域可變配置,如何設計比較好?
