最近需要爬取国家信息安全漏洞共享平台的数据,但是因为我太菜了,所以无论如何也无法绕过CNVD的反爬,所以只好使用selenium来绕过反爬了,虽然效率低,但也算爬下来了。
我用的代理是熊猫代理,主要是我需要的也不多,而且都是短效ip,所以买的熊猫代理2元1000的,也可以根据实际情况自行更改
代码写的非常乱,稍微测试了一下能用就直接爬了,越来越懒了
# -*- coding = utf-8 -*-
# @Time : 2021/8/24 21:16
# @Author : DLT
# @File : 分类爬取.py
# @Software : PyCharm
from multiprocessing import Process
from collections import OrderedDict
import time
from selenium import webdriver
from lxml import etree
import requests
from selenium.webdriver import DesiredCapabilities
def verification(ip, port):
# 检验ip是否有效
ips = ip + ':' + port
proxy = {
'http': 'http://{}'.format(ips),
'https': 'http://{}'.format(ips)
}
# '''head 信息'''
head = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36',
'Connection': 'keep-alive'}
# '''http://icanhazip.com会返回当前的IP地址'''
try:
p = requests.get('http://icanhazip.com', headers=head, proxies=proxy, timeout=10)
if p.status_code == 200:
# 我发现,返回200都不一定是能够用的,所以还得判断输出内容是否是所使用的代理ip
if ip == str(p.text.strip()):
return True
return False
except:
return False
def ipconfig():
chrome_options = webdriver.ChromeOptions()
# 获取ip并验证是否有效
while (1):
try:
ipcon = requests.get(
"代理API").json() # 从熊猫代理获取ip
#每个代理的返回方式不一样,自行修改
ip = ipcon["obj"][0]["ip"]
port = ipcon["obj"][0]["port"]
# print(ip, port)
except:
continue
if verification(ip, port):
break
else:
print("ip无效,将再次请求")
time.sleep(1) # 因为熊猫代理的请求每秒最多一次,此处必须暂停1s
pass
ips = ip + ':' + port
chrome_options.add_argument(
('--proxy-server=' + ips)) # 有的博客写的是'--proxy-server=http://'
# 以下两行为无窗口模式,加上就不会出现谷歌窗口
# chrome_options.add_argument('--headless')
# chrome_options.add_argument('--no-sandbox')
preferences = {
"directory_upgrade": True,
"safebrowsing.enabled": True,
#下载文件的位置:
'download.default_directory': 'F:\爬虫数据\国家信息安全'}
chrome_options.add_experimental_option("prefs", preferences)
try:
driver = webdriver.Chrome(chrome_options=chrome_options)
except:
print("失败")
return driver
def main(n, m):
#f为每页有多少条数据,经过检测,因为ip有效时间仅为一分钟,且网站在连续请求20次后会因访问频率过高而禁止访问,所以20为最合适的数值
f = 0
'''
此处更改url, 只需更改typeId后的数字
'''
while (n < m):
driver = ipconfig()
driver.set_page_load_timeout(15)
driver.set_script_timeout(15)
driver.implicitly_wait(15)
# 加入以下代码跳过js验证
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
})
"""
})
# s为错误计算,如果在连续15次的情况下未请求到数据,那么将会判定未ip失效,将更换ip重新请求
s = 0
#自行修改url
url = "https://www.cnvd.org.cn/flaw/typeResult?typeId=28&max=20&offset=" + str(n * 20)
try:
driver.get(url)
time.sleep(1)
try:
if f >= 20:
f = 0
while f < 20:
try:
xmls = driver.find_elements_by_xpath("//td[@width='45%']/a")
xmls[f].click()
time