import requests
from bs4 import BeautifulSoup
import lxml
import telnetlib #验证代理的可用性
import pymysql.cursors
import random
import threading BASEURL = 'http://www.xicidaili.com/' #西刺首页
urls = [BASEURL+ 'nn/',BASEURL+'nt/',BASEURL+'wn/',BASEURL+'wt/']#西刺分组(more)的ip信息链接列表 #请求头信息,必须有User-Agent
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'} #proxies = {'https': 'http://123.57.85.224:80', 'http': 'http://123.57.85.224:80'} #获得与数据库的连接和游标
def get_cc():
# 连接MySQL数据库
connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root', db='iptables',
charset='utf8', cursorclass=pymysql.cursors.DictCursor)
# 通过cursor创建游标
cursor = connection.cursor()
return connection,cursor #保存ip_port到数据库
def save_ip_port(ip_port):
connection,cursor = get_cc()
try:
sql = 'insert into iptable(ip_port) values("'+ip_port+'")'
cursor.execute(sql)
except:
print('保存'+ip_port+'失败!!!!!')
else:
connection.commit()
connection.close() #从数据库获得ip_port
def get_ip_port():
connection,cursor = get_cc()
sql_get_id = 'select id,ip_port from iptable'
cursor.execute(sql_get_id)
#fetchone()是查询一条数据
id_list = cursor.fetchall()#得到所有的id的字典列表
i = random.randint(0,len(id_list)-1)
id_num = id_list[i]['id']
ip_port = id_list[i]['ip_port'] #获得所有可用的代理 return id_num,ip_port#返回id和ip_port:192.168.1.2:8080 #删除被封的ip_port
def del_ip_port(id_num):
connection,cursor = get_cc()
try:
sql = 'delete from iptable where id = ' + str(id_num)
cursor.execute(sql)
except:
print('删除'+ip_port+'失败!!!!!')
else:
connection.commit()
connection.close() #获得代理
def get_proxies(ip_port):#ip_port = '192.168.2.45:8088'
proxy_ip = 'http://' + ip_port
proxy_ips = 'https://' + ip_port
proxies = {'https': proxy_ips, 'http': proxy_ip}
return proxies #获得对应url分类的最大页码
def get_max_pagenum(url): #url是more(分类)的链接,/nn,/nt.... response = requests.get(url,headers = headers)
status_code = response.status_code
soup = BeautifulSoup(response.content,'lxml')
max_pagenum = soup.find('div',attrs = {'class':'pagination'}).find_all('a')[-2].string
max_pagenum = int(max_pagenum)
return max_pagenum #验证代理是否有用,ip_port = '192.168.2.45:8088'
#每得到一个ip_port都要进行验证,如果可用则保存,否则抛弃
def verifyProxyList(ip_port):
url = 'http://www.baidu.com'
# proxies = { "http": "http://"+ ip_port }
host ,port = ip_port.split(':')
try:
# res = requests.get(url,headers = headers,proxies = proxies,timeout = 5.0)
telnetlib.Telnet(host, port=port, timeout=5)
except:
print('---Failur:' + ip_port)
else:
#ips.append(ip_port)#这里应该存储到Redis等数据库中
save_ip_port(ip_port) def main(url,proxies):#这里是more的链接,/nn/1,/nn/2.... try:
response = requests.get(url,headers = headers,proxies = proxies,timeout = 5.0)
status_code = response.status_code #503说明ip被封 if(status_code != requests.codes.ok):#响应的不是正常状态
#删除旧的代理ip_port,这里还需要验证是否有bug
old_ip_port = proxies['http'][7:]
del_ip_port(old_ip_port)
#修改代理,重新请求
id_num,ip_port = get_ip_port()
proxies = get_proxies(ip_port)
print(str(proxies))
return soup = BeautifulSoup(response.content,'lxml') results = soup.find_all('tr')#遍历所有的tr for result in results[1:]:#这里第一个tr子标签是th,所以会报错
tdlist = result.find_all('td')
ip_port = tdlist[1].string+':'+tdlist[2].string
verifyProxyList(ip_port)
except:
print('请求异常......') class myThread(threading.Thread):
def __init__(self, threadID, name, url):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.url = url def run(self):
print('正在执行线程:'+self.name)#没有验证这一行的可行性
id_num,ip_port = get_ip_port()
proxies = get_proxies(ip_port)
max_pagenum = get_max_pagenum(self.url)
#print(max_pagenum)
for i in range(1,max_pagenum):
url = self.url + '/' + str(i)
main(url,proxies) #4线程爬取西刺的ip代理池
if __name__ == '__main__': t1 = myThread(1,"Thread-1",urls[0])
t2 = myThread(2,"Thread-2",urls[1])
t3 = myThread(3,"Thread-3",urls[2])
t4 = myThread(4,"Thread-4",urls[3])
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()

Python四线程爬取西刺代理的更多相关文章

  1. 使用XPath爬取西刺代理

    因为在Scrapy的使用过程中,提取页面信息使用XPath比较方便,遂成此文. 在b站上看了介绍XPath的:https://www.bilibili.com/video/av30320885?fro ...

  2. 手把手教你使用Python爬取西刺代理数据(下篇)

    /1 前言/ 前几天小编发布了手把手教你使用Python爬取西次代理数据(上篇),木有赶上车的小伙伴,可以戳进去看看.今天小编带大家进行网页结构的分析以及网页数据的提取,具体步骤如下. /2 首页分析 ...

  3. Scrapy爬取西刺代理ip流程

    西刺代理爬虫 1. 新建项目和爬虫 scrapy startproject daili_ips ...... cd daili_ips/ #爬虫名称和domains scrapy genspider ...

  4. python scrapy 爬取西刺代理ip(一基础篇)(ubuntu环境下) -赖大大

    第一步:环境搭建 1.python2 或 python3 2.用pip安装下载scrapy框架 具体就自行百度了,主要内容不是在这. 第二步:创建scrapy(简单介绍) 1.Creating a p ...

  5. python+scrapy 爬取西刺代理ip(一)

    转自:https://www.cnblogs.com/lyc642983907/p/10739577.html 第一步:环境搭建 1.python2 或 python3 2.用pip安装下载scrap ...

  6. python3爬虫-通过requests爬取西刺代理

    import requests from fake_useragent import UserAgent from lxml import etree from urllib.parse import ...

  7. 爬取西刺ip代理池

    好久没更新博客啦~,今天来更新一篇利用爬虫爬取西刺的代理池的小代码 先说下需求,我们都是用python写一段小代码去爬取自己所需要的信息,这是可取的,但是,有一些网站呢,对我们的网络爬虫做了一些限制, ...

  8. 爬取西刺网的免费IP

    在写爬虫时,经常需要切换IP,所以很有必要自已在数据维护库中维护一个IP池,这样,就可以在需用的时候随机切换IP,我的方法是爬取西刺网的免费IP,存入数据库中,然后在scrapy 工程中加入tools ...

  9. scrapy爬取西刺网站ip

    # scrapy爬取西刺网站ip # -*- coding: utf-8 -*- import scrapy from xici.items import XiciItem class Xicispi ...

随机推荐

  1. SSL SSH

    http://www.91ri.org/13679.html https://www.linux.com/blog/how-install-ssl-certificate-linux-server h ...

  2. 每天学习一个Linux命令-目录

    在工作中总会零零散散使用到各种Linux命令,从今天开始详细的学习一下linux常用命令,坚持每天一个命令,学习的主要参考资料为: 1.竹子-博客(https://www.cnblogs.com/pe ...

  3. ffmpeg中av_log的实现分析

    [时间:2017-10] [状态:Open] [关键词:ffmpeg,avutil,av_log, 日志输出] 0 引言 FFmpeg的libavutil中的日志输出的接口整体比较少,但是功能还是不错 ...

  4. 【iCore4 双核心板_uC/OS-II】例程十:信号量集

    一.实验说明: 在实际应用中,任务常常需要与多个事件同步,即要根据多个信号量组合作用的结果来决定任务的运行方式.UCOSII为了实现多个信号量组合的功能定义了一种特殊的数据结构——信号量集. 二.实验 ...

  5. JavaScript之JS的数据类型

    前言 JavaScript一共有6中数据类型: 基本数据类型(5):字符串(String).数字(Number).布尔(Boolean).数组(Array).空(Null).未定义(Undefined ...

  6. MySQL加密解密

    1. 加密:mysql323,不可逆 select old_password('bbs.antian365.com'); # 10c886615b135b38 2. 加密:mysqlsha1,不可逆 ...

  7. ubuntu16.04 在/etc/network/interfaces设置static ip无效

    双网卡使用无线网卡上互联网,使用以太网卡连局域网,在/etc/network/interfaces里对以太网卡设置static ip无效,使用ifconfig临时设置也仅能工作一会,设置的ip马上就消 ...

  8. 三维计算机视觉 —— 中层次视觉 —— RCNN Family

    RCNN是从图像中检测物体位置的方法,严格来讲不属于三维计算机视觉.但是这种方法却又非常非常重要,对三维物体的检测非常有启发,所以在这里做个总结. 1.RCNN - the original idea ...

  9. phpstorm webstorm 常用快捷键总结

    1.全项目搜索 ctrl + shift + F  这个是window下的快捷键

  10. thymeleaf入门和学习

    springboot框架不推荐使用jsp,一方面是兼容性的技术问题,一方面也是其前后端整合在一起,很难适合当下大规模的网站开发环境.HTML只是一种标记语言,并不具有获取model中数据的功能,所以视 ...