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 ...
随机推荐
- HADOOP security
https://www.microsoft.com/en-us/trustcenter/security/azure-security https://docs.microsoft.com/en-us ...
- OSPF进程号的意义及多进程OSPF
OSPF进程号的意义及多进程OSPF—吴锦霖分享 1. OSPF进程号的概念 在配置OSPF时,我们采用的是router ospf命令,在该命令后面需要加上这个OSPF进程的进程号(Proces ...
- Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project demo: Fatal error com piling: 无效的标记: -parameters
背景:本项目使用JDK1.8 编译maven工程的时候出现如下错误: Failed to execute goal org.apache.maven.plugins:maven-compiler-pl ...
- 五、005-环境安装【docker、fabric】
1.参考地址:https://hyperledger-fabric.readthedocs.io/en/latest/prereqs.html#install-curl 一.前置条件和系统配置 1.安 ...
- springboot-aop
AOP(面向切面编程)是Spring的两大核心功能之一,功能非常强大,为解耦提供了非常优秀的解决方案. 现在就以springboot中aop的使用来了解一下如何使用aop. 写几个简单的Spring ...
- SpringBoot------ActiveMQ安装
1.官网下载地址 http://activemq.apache.org/activemq-5156-release.html springboot文档 https://docs.spring.io/s ...
- Easy UI combogrid动态加载数据
场景: datagrid的每一行允许编辑,一行中有一个字段,编辑时,提供下拉框选项,供选择. 下拉框选项有多个列.如下图所示:(点击红框内的下拉按钮,会弹出绿框内的内容) 要求: 每行弹出的下拉框内容 ...
- 如何建立nfs网络文件系统
建立网络文件系统的前提:windows与linux虚拟机及开发板三者之间能够互相ping 通. 三者互ping通IP设置举例: 1. 首先,关闭windows的防火墙,然后通过:ufw disab ...
- linux signal
1) SIGHUP 本信号在用户终端连接(正常或非正常)结束时发出, 通常是在终端的控制进程结束时, 通知同一session内的各个作业, 这时它们与控制终端不再关联. 登录Linux时,系统会分配给 ...
- h5 ios手机 隐藏input输入光标
前面在做一个H5中用到的6位数字密码弹框(类似支付.微信那种)时,遇到一个可怕问题,那就是在浏览器和安卓中是不显示输入光标的,但是在ios手机上光标总是能看见,像穿透一样地显示最外层. 先说下实现密码 ...