Python四线程爬取西刺代理
- 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四线程爬取西刺代理的更多相关文章
- 使用XPath爬取西刺代理
因为在Scrapy的使用过程中,提取页面信息使用XPath比较方便,遂成此文. 在b站上看了介绍XPath的:https://www.bilibili.com/video/av30320885?fro ...
- 手把手教你使用Python爬取西刺代理数据(下篇)
/1 前言/ 前几天小编发布了手把手教你使用Python爬取西次代理数据(上篇),木有赶上车的小伙伴,可以戳进去看看.今天小编带大家进行网页结构的分析以及网页数据的提取,具体步骤如下. /2 首页分析 ...
- Scrapy爬取西刺代理ip流程
西刺代理爬虫 1. 新建项目和爬虫 scrapy startproject daili_ips ...... cd daili_ips/ #爬虫名称和domains scrapy genspider ...
- python scrapy 爬取西刺代理ip(一基础篇)(ubuntu环境下) -赖大大
第一步:环境搭建 1.python2 或 python3 2.用pip安装下载scrapy框架 具体就自行百度了,主要内容不是在这. 第二步:创建scrapy(简单介绍) 1.Creating a p ...
- python+scrapy 爬取西刺代理ip(一)
转自:https://www.cnblogs.com/lyc642983907/p/10739577.html 第一步:环境搭建 1.python2 或 python3 2.用pip安装下载scrap ...
- python3爬虫-通过requests爬取西刺代理
import requests from fake_useragent import UserAgent from lxml import etree from urllib.parse import ...
- 爬取西刺ip代理池
好久没更新博客啦~,今天来更新一篇利用爬虫爬取西刺的代理池的小代码 先说下需求,我们都是用python写一段小代码去爬取自己所需要的信息,这是可取的,但是,有一些网站呢,对我们的网络爬虫做了一些限制, ...
- 爬取西刺网的免费IP
在写爬虫时,经常需要切换IP,所以很有必要自已在数据维护库中维护一个IP池,这样,就可以在需用的时候随机切换IP,我的方法是爬取西刺网的免费IP,存入数据库中,然后在scrapy 工程中加入tools ...
- scrapy爬取西刺网站ip
# scrapy爬取西刺网站ip # -*- coding: utf-8 -*- import scrapy from xici.items import XiciItem class Xicispi ...
随机推荐
- mybatis-plus快速入门使用
目前正在维护的公司的一个项目是一个ssm架构的java项目,dao层的接口有大量数据库查询的方法,一个条件变化就要对应一个方法,再加上一些通用的curd方法,对应一张表的dao层方法有时候多达近20个 ...
- React Native常用组件之ListView
1. ListView常用属性 ScrollView 相关属性样式全部继承 dataSource ListViewDataSource 设置ListView的数据源 initialListSize n ...
- docker容器添加微软雅黑字体
添加中文字体其实很简单,往容器里COPY一个ttf字体文件就生效了,不需要执行fc-cache. 基于debian 8的tomcat容器,Dockerfile: COPY msyh.ttf /usr/ ...
- 关于Unity中物体分别在本地和世界坐标系对应方向的移动
方向 Vector3可以定义以世界坐标轴为参考的三维矢量,Vector3.forward,Vector3.up,Vector3.right方别对应物体世界坐标系的Z,Y,X轴方向的单位向量,或者叫三维 ...
- jedis中scan的实现
我的版本说明: redis服务端版本:redis_version:2.8.19 jedis: <dependency> <groupId>redis.clients</g ...
- MISCONF Redis is configured to save RDB snapshots, but it is currently not able to persist on disk. Commands that may modify the data set are disabled, because this instance is configured to report e
早上来到公司,线上的项目报错: Error in execution; nested exception is io.lettuce.core.RedisCommandExecutionExcepti ...
- Go VSCode配置编译task
菜单栏Tasks->Configure Tasks { "version": "2.0.0", "tasks": [ { " ...
- JS中实现种子随机数
参数: 详谈JS中实现种子随机数及作用 我在Egret里这么写... class NumberTool{ /**种子(任意默认值5)*/ public static seed:number = 5; ...
- 关于windows 下每次打开IE 8都弹出欢迎使用Internet Explorer 8 弹窗的关闭方法
今天笔者在安装完windows 操作系统后,发现了一个问题,即每次打开IE 8浏览器,都会弹出一个欢迎界面: 弹窗标题为:设置windows Internet Explorer,具体内容如下图所示: ...
- Python __all__变量用法
Python中一个py文件就是一个模块,“__all__”变量是一个特殊的变量,可以在py文件中,也可以在包的__init__.py中出现. 1.在普通模块中使用时,表示一个模块中允许哪些属性可以被导 ...