selenium抓不到对应图片
来源:10-6 滑动验证码识别 和selenium模拟登录B站 - 1

超级无敌大好人
2022-06-05
**老师您好,我发现B站不用滑块,然后豆瓣在用 我就修改了课程代码,代码如下,然后我发现图片抓取的是上面那张灰色的,没有抓取到下面真正的图片,不知道怎么解决,希望老师帮忙看下
import time
from io import BytesIO
import random
import requests
from selenium import webdriver
from selenium.webdriver import ActionChains
from PIL import Image
url = “https://www.douban.com/”
browser = webdriver.Chrome(executable_path=r"C:\Users\XUEJINHU\Desktop\编程\python\配件\chromedriver_win32\chromedriver.exe")
#2. 点击元素显示出有缺口的图片并下载
#3. 对比两张图片找出缺口的移动像素
#4. 拖动元素
url = “https://www.douban.com/”
def compare_pixel(image1, image2, i, j):
#判断两个像素是否相同
pixel1 = image1.load()[i, j]
pixel2 = image2.load()[i, j]
threshold = 60
if abs(pixel1[0] - pixel2[0]) < threshold and abs(pixel1[1] - pixel2[1]) < threshold and abs(pixel1[2] - pixel2[2]) < threshold:
return True
return False
def crop_image(image_file_name):
#截图验证码图片
#定位某个元素在浏览器中的位置
time.sleep(2)
img = browser.find_element_by_xpath(’//*[@class=“tc-imgarea drag”]/div[@id=“slideBgWrap”]/img’)
time.sleep(2)
location = img.location
print("图片的位置", location)
size = img.size
top, buttom, left, right = location["y"], location["y"]+size["height"], location["x"], location['x'] + size["width"]
print("验证码位置", left,top, right, buttom)
screenshot = browser.get_screenshot_as_png()
screenshot = Image.open(BytesIO(screenshot))
captcha = screenshot.crop((int(left),int(top), int(right), int(buttom)))
captcha.save(image_file_name)
return captcha
def login():
username = "19818509172"
password = “1111111”
browser.get(url)
browser.maximize_window() #很重要!!
time.sleep(0.5)
browser.switch_to.frame(browser.find_element_by_tag_name("iframe"))
log_ele = browser.find_element_by_xpath('/html/body/div[1]/div[1]/ul[1]/li[2]').click()
time.sleep(0.5)
username_ele = browser.find_element_by_xpath('//*[@id="username"]')
password_ele = browser.find_element_by_xpath('//*[@id="password"]')
username_ele.send_keys(username)
password_ele.send_keys(password)
click_ele = browser.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/div[5]/a').click()
time.sleep(4)
browser.switch_to.frame(browser.find_element_by_xpath('//*[@id="tcaptcha_iframe"]'))
slider = browser.find_element_by_xpath('//*[@id="tcaptcha_drag_thumb"]')
ActionChains(browser).move_to_element(slider).perform()
#如果截取图片
image1 = crop_image("captcha1.png")
#获取缺口图片
ActionChains(browser).click_and_hold(slider).perform()
if name == “main”:
login()
2回答
-
bobby
2022-06-07
我这里看到的路径是这样的,和你写的好像不一样
062022-06-10 -
超级无敌大好人
提问者
2022-06-05
老师,我又试了试
js = '$("img").attr("aria-hidden","false")' js1 = '$("img").removeClass("unselectable")' # js2 = '$(".tc-bg-placeholder").remove()' js3 = '$(".tc-bg-placeholder").attr("type", "hidden")'
还是不行
00
相似问题