基于selenium的 bilibili登录爬虫, 解决汉字验证的问题
Posted gyse
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于selenium的 bilibili登录爬虫, 解决汉字验证的问题相关的知识,希望对你有一定的参考价值。
b站近日把登录页面的验证方式从滑块验证改为了汉字验证,我看网上也没用相关的爬虫教程,所以自己写了一个,作为b站爬虫参考。
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from chaojiying import Chaojiying_Client class Bilibili: def __init__(self, username, password, user): # 基本配置 self.username = username self.password = password self.url = ‘https://passport.bilibili.com/login‘ # 浏览器配置 self.driver = webdriver.Chrome() self.driver.maximize_window() self.driver.implicitly_wait(10) # 打开登录页面 def start(self): self.driver.get(self.url) # 获取用户名和密码的输入框 login_username = self.driver.find_element_by_id("login-username") login_password = self.driver.find_element_by_id("login-passwd") # 输入用户名和密码,并点击登录 login_username.send_keys(self.username) login_password.send_keys(self.password) self.driver.find_element_by_css_selector("a.btn.btn-login").click() # 获取验证码图片,这里用第三方打码平台 超级鹰 进行图片的汉字解析,返回图片里面汉字的坐标 def img(self): self.start() self.img = WebDriverWait(self.driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, ‘body > div.geetest_panel.geetest_wind > div.geetest_panel_box.geetest_no_logo.geetest_panelshowclick > div.geetest_panel_next > div > div > div.geetest_table_box > div.geetest_window > div > div.geetest_item_wrap > img‘))) time.sleep(3) self.img_src = self.img.get_attribute("src") res = requests.get(self.img_src) # 这里是用超级鹰进行汉字解析 chaojiying = Chaojiying_Client(‘xxx‘, ‘xxx‘, ‘xxx‘) im = res.content # 返回超级鹰的解析的图片的坐标 self.locations = [[int(number) for number in group.split(‘,‘)] for group in chaojiying.PostPic(im, 9004)[‘pic_str‘].split(‘|‘)] # 拿到坐标用selenium进行点击 # 注意拿到的坐标不准确, 因为给 超级鹰 进行解析的图片, 和你登录页面的图片不是同一个图片, 大小因浏览器窗口大小有差异, 我这里是相差1.3倍,你要自己计算 def words_click(self): for location in self.locations: ActionChains(self.driver).move_to_element_with_offset(self.img, location[0]/1.3, location[1]/1.3).click().perform() time.sleep(0.5) btn = self.driver.find_element_by_css_selector("body > div.geetest_panel.geetest_wind > div.geetest_panel_box.geetest_no_logo.geetest_panelshowclick > div.geetest_panel_next > div > div > div.geetest_panel > a > div") btn.click()
以上是关于基于selenium的 bilibili登录爬虫, 解决汉字验证的问题的主要内容,如果未能解决你的问题,请参考以下文章
Python爬虫:Bilibili模拟登陆(滑动验证码)项目
[Python爬虫] Selenium实现自动登录163邮箱和Locating Elements介绍