使用selenium爬取CNVD

最近需要爬取国家信息安全漏洞共享平台的数据,但是因为我太菜了,所以无论如何也无法绕过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
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
# -*- coding:utf-8 -*- import sys #print (u'系统默认编码为',sys.getdefaultencoding()) default_encoding = 'utf-8' #重新设置编码方式为uft-8 if sys.getdefaultencoding() != default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) #print (u'系统默认编码为',sys.getdefaultencoding()) import requests from bs4 import BeautifulSoup import traceback import re import xlwt def getURLDATA(url): #url = 'http://www.cnnvd.org.cn/web/xxk/ldxqById.tag?CNNVD=CNNVD-201901-1014' header={ 'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36', 'Connection': 'keep-alive',} r=requests.get(url,headers=header,timeout=30) #r.raise_for_status()抛出异常 html = BeautifulSoup(r.content.decode(),'html.parser') link=html.find(class_='detail_xq w770')#漏洞信息详情 link_introduce=html.find(class_='d_ldjj')#漏洞简介 link_others=html.find_all(class_='d_ldjj m_t_20')#其他 #print(len(link_introduce)) try: #print ("危害等级:"+link.contents[3].contents[3].find('a').text.lstrip().rstrip())#危害等级 list4.append(str(link.contents[3].contents[3].find('a').text.lstrip().rstrip())) except: #print("危害等级:is empty") list4.append("") try: #print ("CVE编号:"+link.contents[3].contents[5].find('a').text.lstrip().rstrip())#CVE编号 list5.append(str(link.contents[3].contents[5].find('a').text.lstrip().rstrip())) except: #print("CVE编号:is empty") list5.append("") try: #print ("漏洞类型:"+link.contents[3].contents[7].find('a').text.lstrip().rstrip())#漏洞类型 list6.append(str(link.contents[3].contents[7].find('a').text.lstrip().rstrip())) except : #print("漏洞类型:is empty") list6.append("") try: #print ("发布时间:"+link.contents[3].contents[9].find('a').text.lstrip().rstrip())#发布时间 list7.append(str(link.contents[3].contents[9].find('a').text.lstrip().rstrip())) except : #print("发布时间:is empty") list7.append("") try: #print ("威胁类型:"+link.contents[3].contents[11].find('a').text.lstrip().rstrip())#威胁类型 list8.append(str(link.contents[3].contents[11].find('a').text.lstrip().rstrip())) except : #print("威胁类型:is empty") list8.append("") try: #print ("更新时间:"+link.contents[3].contents[13].find('a').text.lstrip().rstrip())#更新时间 list9.append(str(link.contents[3].contents[13].find('a').text.lstrip().rstrip())) except : #print("更新时间:is empty") list9.append("") try: #print ("厂商:"+link.contents[3].contents[15].find('a').text.lstrip().rstrip())#厂商 list10.append(str(link.contents[3].contents[15].find('a').text.lstrip().rstrip())) except: #print("厂商:is empty") list10.append("") #link_introduce=html.find(class_='d_ldjj')#漏洞简介 try: link_introduce_data=BeautifulSoup(link_introduce.decode(),'html.parser').find_all(name='p') s="" for i in range(0,len(link_introduce_data)): ##print (link_introduce_data[i].text.lstrip().rstrip()) s=s+str(link_introduce_data[i].text.lstrip().rstrip()) #print(s) list11.append(s) except : list11.append("") if(len(link_others)!=0): #link_others=html.find_all(class_='d_ldjj m_t_20') #print(len(link_others)) try: #漏洞公告 link_others_data1=BeautifulSoup(link_others[0].decode(),'html.parser').find_all(name='p') s="" for i in range(0,len(link_others_data1)): ##print (link_others_data1[i].text.lstrip().rstrip()) s=s+str(link_others_data1[i].text.lstrip().rstrip()) #print(s) list12.append(s) except: list12.append("") try: #参考网址 link_others_data2=BeautifulSoup(link_others[1].decode(),'html.parser').find_all(name='p') s="" for i in range(0,len(link_others_data2)): ##print (link_others_data2[i].text.lstrip().rstrip()) s=s+str(link_others_data2[i].text.lstrip().rstrip()) #print(s) list13.append(s) except: list13.append("") try: #受影响实体 link_others_data3=BeautifulSoup(link_others[2].decode(),'html.parser').find_all('a',attrs={'class':'a_title2'}) s="" for i in range(0,len(link_others_data3)): ##print (link_others_data3[i].text.lstrip().rstrip()) s=s+str(link_others_data3[i].text.lstrip().rstrip()) #print(s) list14.append(s) except: list14.append("") try: #补丁 link_others_data3=BeautifulSoup(link_others[3].decode(),'html.parser').find_all('a',attrs={'class':'a_title2'}) s="" for i in range(0,len(link_others_data3)): ##print (link_others_data3[i].t

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值