python反爬-图像验证码与滑块验证码的跳过、反selenium检测,动态ip
一、滑块验证码的跳过
以某网站为例,要查看每条信息,需要点击查看后完成滑块验证码的跳过
本文主要selenium模拟浏览器的方式,模拟网页操作,要获取所有信息就需要翻页,因此打开F12检查总页数对应的xpath节点,由下图可以观察到总页数的信息已经包含在了html网页上,因此先使用BeautifulSoup
获取该网页信息,获取总页数,以便执行翻页的循环.
先通过BeautifulSoup获取总页码,需要观察上图页码所在位置对应的节点,页码参数对应的位置是text位置
import pandas as pd
from bs4 import BeautifulSoup
import requests
#获取验证码图片
url='该网页的url'
response= requests.get(url)
response.encoding='utf-8'
raw_data=response.text
soup = BeautifulSoup(raw_data, 'html.parser')
#先定位到class=key的div节点
key_content = soup.find('div',class_='key')
#再定位到align='center'的td表格
total_page=key_content.find('td',align='center')
#找到文本共.*条中间的数字
total_page_num=int(re.findall(r'当前 1/(\d+) 页',total_page.text)[0])
找到总页码后,就可以开始执行循环,每次循环获取当前页面所有信息,然后就点击翻页。
先导入selenium所需要的库
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
下面进行每页信息的获取
获取每页信息需要点击查看
按钮,因此我们需要定位到该按钮对应的节点,检查该按钮的元素,可以得到节点内容是
<input class="ck" type="button" onclick="doview('2407-410523-04-01-709156')" value="查看">
并且我们可以看到下一个查看按钮的节点内容除了onclick参数里面的内容其余都是一样的。因此我们在定位这个按钮的时候不要使用onclick参数定位,使用value和class参数一次性定位该页所有的查看按钮。
#打开网页
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.get(url)
观察页面可以发现,第一次进去的时候右下角有一个小弹窗,由于弹窗显示导致一页的所有按钮不会显示,因此先关闭这个弹窗
#定位元素后关闭弹窗
icon_element = driver.find_element(By.CSS_SELECTOR, 'img.demoIcon[οnclick="showOut()"]')
WebDriverWait(driver, 10).until(EC.element_to_be_clickable(icon_element))
icon_element.click(