python爬虫要经历爬虫、爬虫被限制、爬虫反限制的过程。当然后续还要网页爬虫限制优化,爬虫再反限制的一系列道高一尺魔高一丈的过程。

爬虫的初级阶段,添加headers和ip代理可以解决很多问题。

贴代码:说下思路

1、到http://www.xicidaili.com/nn/抓取相应的代理ip地址,地址比较多,但是不保证能用。先保存到列表

2、多线程验证代理ip的可行性,然后写入到对应的txt文件

3、当需要代理ip的时候,倒入模块,执行main()函数,可得到可用的代理ip进行后续功能。

验证ip用到了telnetlib和requests两种方法。建议要爬取哪个网页,直接requests相应网页验证比较好。

#coding:utf-8

from bs4 import BeautifulSoup
import time
import threading
import random
import telnetlib,requests #设置全局超时时间为3s,也就是说,如果一个请求3s内还没有响应,就结束访问,并返回timeout(超时)
import socket
socket.setdefaulttimeout(3) headers = {
"user-agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36",
} def get_ip():
#获取代理IP,返回列表
httpResult=[]
httpsResult=[]
try:
for page in range(1,2):
IPurl = 'http://www.xicidaili.com/nn/%s' %page
rIP=requests.get(IPurl,headers=headers)
IPContent=rIP.text
print IPContent
soupIP = BeautifulSoup(IPContent,'lxml')
trs = soupIP.find_all('tr')
for tr in trs[1:]:
tds = tr.find_all('td')
ip = tds[1].text.strip()
port = tds[2].text.strip()
protocol = tds[5].text.strip()
if protocol == 'HTTP':
httpResult.append( 'http://' + ip + ':' + port)
elif protocol =='HTTPS':
httpsResult.append( 'https://' + ip + ':' + port)
except:
pass
return httpResult,httpsResult
'''
#验证ip地址的可用性,使用telnetlib模块_http
def cip(x,y):
f = open("E:\ip_http.txt","a")
f.truncate()
try:
telnetlib.Telnet(x, port=y, timeout=5)
except:
print('f')
else:
print('---------------------------success')
f.write(x+':'+y+'\n')
#验证ip地址的可用性,使用telnetlib模块_https
def csip(x,y):
f = open("E:\ip_https.txt","a")
f.truncate()
try:
telnetlib.Telnet(x, port=y, timeout=5)
except:
print('f')
else:
print('---------------------------success')
f.write(x+':'+y+'\n')
''' #验证ip地址的可用性,使用requests模块,验证地址用相应要爬取的网页 http
def cip(x,y):
f = open("E:\ip_http.txt","a")
f.truncate()
try:
print (x+y)
requests.get('http://ip.chinaz.com/getip.aspx',proxies={'http':x+":"+y},timeout=3)
except:
print('f')
else:
print('---------------------------success')
f.write(x+':'+y+'\n')
#验证ip地址的可用性,使用requests模块,验证地址用相应要爬取的网页。https
def csip(x,y):
f = open("E:\ip_https.txt","a")
f.truncate()
try:
print (x+y)
requests.get('https://www.lagou.com/',proxies={'https':x+":"+y},timeout=3)
except:
print('f')
else:
print('---------------------------success')
f.write(x+':'+y+'\n') def main():
httpResult,httpsResult = get_ip() threads = []
open("E:\ip_http.txt","a").truncate()
for i in httpResult:
a = str(i.split(":")[-2][2:].strip())
b = str(i.split(":")[-1].strip())
t = threading.Thread(target=cip,args=(a,b,))
threads.append(t) for i in range(len(httpResult)):
threads[i].start()
for i in range(len(httpResult)):
threads[i].join() threads1 = []
open("E:\ip_https.txt","a").truncate()
for i in httpsResult:
a = str(i.split(":")[-2][2:].strip())
b = str(i.split(":")[-1].strip())
t = threading.Thread(target=csip,args=(a,b,))
threads1.append(t) for i in range(len(httpsResult)):
threads1[i].start()
for i in range(len(httpsResult)):
threads1[i].join() if __name__ == '__main__':
main()

python——代理ip获取的更多相关文章

  1. 爬虫的新手使用教程(python代理IP)

    前言 Python爬虫要经历爬虫.爬虫被限制.爬虫反限制的过程.当然后续还要网页爬虫限制优化,爬虫再反限制的一系列道高一尺魔高一丈的过程.爬虫的初级阶段,添加headers和ip代理可以解决很多问题. ...

  2. c# 代理IP获取通用方法

    调用: ConcurrentQueue<string> proxyIpQueue = new ConcurrentQueue<string>(); Grab_ProxyIp(p ...

  3. python通过ip获取地址

    # -*- coding: utf-8 -*- url = "http://ip.taobao.com/service/getIpInfo.php?ip=" #查找IP地址 def ...

  4. PYTHON代理IP

    import urllib.request url = 'http://www.whatismyip.com.tw/' proxy_support = urllib.request.ProxyHand ...

  5. 使用TaskManager爬取2万条代理IP实现自动投票功能

    话说某天心血来潮想到一个问题,朋友圈里面经常有人发投票链接,让帮忙给XX投票,以前呢会很自觉打开链接帮忙投一票.可是这种事做多了就会考虑能不能使用工具来进行投票呢,身为一名程序猿决定研究解决这个问题. ...

  6. 写了个小爬虫,为何用上代理ip总是出现错误。

    import urllib.request import re import os import random import threading def url_open(url): #在第8到第12 ...

  7. 代理 IP 云打码平台的使用

    代理ip 获取代理ip的网站: 快代理 西祠代理 www.goubanjia.com #代理ip import requests headers = { 'User-Agent':'Mozilla/5 ...

  8. python爬虫实战(一)——实时获取代理ip

    在爬虫学习的过程中,维护一个自己的代理池是非常重要的. 详情看代码: 1.运行环境 python3.x,需求库:bs4,requests 2.实时抓取西刺-国内高匿代理中前3页的代理ip(可根据需求自 ...

  9. python编写的自动获取代理IP列表的爬虫-chinaboywg-ChinaUnix博客

    python编写的自动获取代理IP列表的爬虫-chinaboywg-ChinaUnix博客 undefined Python多线程抓取代理服务器 | Linux运维笔记 undefined java如 ...

随机推荐

  1. Keras(二)Application中五款已训练模型、VGG16框架解读

    Application的五款已训练模型 + H5py简述 Keras的应用模块Application提供了带有预训练权重的Keras模型,这些模型可以用来进行预测.特征提取和finetune. 后续还 ...

  2. 【Nginx】四层负载均衡配置

    一.概述 二.配置 2.1 环境准备 2.2 安装及配置 1).下载Nginx 2).下载nginx_tcp_proxy_module 插件 3).编译Nginx 4).修改Nginx.conf配置文 ...

  3. spring security集成cas实现单点登录

    spring security集成cas 0.配置本地ssl连接 操作记录如下: =====================1.创建证书文件thekeystore ,并导出为thekeystore.c ...

  4. 20182324 实验一《Linux基础与Java开发环境》实验报告

    20182324 2019-2020-1 <数据结构与面向对象程序设计>实验1报告 课程:<程序设计与数据结构> 班级: 1823 姓名: 殷宇豪 学号: 20182324 实 ...

  5. Flutter开发环境配置(MAC版)

    一.配置镜像 打开命令终端,输入命令open ~/.bash_profile,打开bash_profile文本,添加镜像路径并保存 export PUB_HOSTED_URL=https://pub. ...

  6. C#中using的使用-以FileStream写入文件为例

    场景 CS中FileStream的对比以及使用方法: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/100396022 关注公众号 ...

  7. apache ignite系列(四):持久化

    ignite持久化与固化内存 1.持久化的机制 ignite持久化的关键点如下: ignite持久化可防止内存溢出导致数据丢失的情况: 持久化可以定制化配置,按需持久化; 持久化能解决在大量缓存数据情 ...

  8. Nightmare Ⅱ(双向BFS)

    Problem Description Last night, little erriyue had a horrible nightmare. He dreamed that he and his ...

  9. 装系统 ---------- 了解 UEFI与Legacy、硬盘分区MBR和GPT

    UEFI:全称“统一的可扩展固件接口”(Unified Extensible Firmware Interface),一种详细描述类型接口的标准.这种接口用于操作系统自动从预启动的操作环境,加载到一种 ...

  10. 松软科技课堂:数据库-主键(PrimaryKey)

    主键就是一个表中每个数据行的唯一标识.不会有重复值的列才能当主键.一个表可以没有主键,但是会非常难以处理,因此没有特殊理由表都要设定主键 主键有两种选用策略:业务主键和逻辑主键.业务主键是使用有业务意 ...