#       2019/9/8
# 思路: 1、找到一个免费的ip代理网站(如:西刺代理)
#
# 2、爬取ip(常规爬取requests+BeautifulSoup)
#
# 3、验证ip有效性(携带爬取到的ip,去访问指定的url,看返回的状态码是不是200)
#
# 4、记录ip (写到文档) # !/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests, threading, datetime
from bs4 import BeautifulSoup
import random """
1、抓取西刺代理网站的代理ip
2、并根据指定的目标url,对抓取到ip的有效性进行验证
3、最后存到指定的path
""" # ------------------------------------------------------文档处理--------------------------------------------------------
# 写入文档
def write(path, text):
with open(path, 'a', encoding='utf-8') as f:
f.writelines(text)
f.write('\n')
f.close() # 清空文档
def truncatefile(path):
with open(path, 'w', encoding='utf-8') as f:
f.truncate() # 读取文档
def read(path):
with open(path, 'r', encoding='utf-8') as f:
txt = []
for s in f.readlines():
txt.append(s.strip())
return txt # ----------------------------------------------------------------------------------------------------------------------
# 计算时间差,格式: 时分秒
def gettimediff(start, end):
seconds = (end - start).seconds
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
diff = ("%02d:%02d:%02d" % (h, m, s))
return diff # ----------------------------------------------------------------------------------------------------------------------
# 返回一个随机的请求头 headers
def getheaders():
user_agent_list = [ \
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1" \
"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11", \
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6", \
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6", \
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1", \
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5", \
"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5", \
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", \
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", \
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", \
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", \
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", \
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", \
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", \
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", \
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3", \
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24", \
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"
]
UserAgent = random.choice(user_agent_list)
headers = {'User-Agent': UserAgent}
return headers # -----------------------------------------------------检查ip是否可用----------------------------------------------------
def checkip(targeturl, ip):
headers = getheaders() # 定制请求头
proxies = {"http": "http://" + ip, "https": "http://" + ip} # 代理ip
try:
response = requests.get(url=targeturl, proxies=proxies, headers=headers, timeout=5).status_code
if response == 200:
return True
else:
return False
except:
return False # -------------------------------------------------------获取代理方法----------------------------------------------------
# 免费代理 XiciDaili
def findip(type, pagenum, targeturl, path): # ip类型,页码,目标url,存放ip的路径
list = {'1': 'http://www.xicidaili.com/wn/', # xicidaili国内https代理
'2': 'http://www.xicidaili.com/nn/', # xicidaili国内高匿代理
'3': 'http://www.xicidaili.com/nt/', # xicidaili国内普通代理
'4': 'http://www.xicidaili.com/wt/'} # xicidaili国外http代理
url = list[str(type)] + str(pagenum) # 配置url
# print("url:",url)
headers = getheaders() # 定制请求头
html = requests.get(url=url, headers=headers, timeout=5).text
# print("html:", html)
soup = BeautifulSoup(html, 'lxml')
all = soup.find_all('tr', class_='odd')
for i in all:
t = i.find_all('td')
ip = t[1].text + ':' + t[2].text
is_avail = checkip(targeturl, ip)
if is_avail == True:
write(path=path, text=ip)
print(ip) # -----------------------------------------------------多线程抓取ip入口---------------------------------------------------
def getip(targeturl, path):
truncatefile(path) # 爬取前清空文档
start = datetime.datetime.now() # 开始时间
threads = []
for type in range(1): # 四种类型ip,每种类型取前三页,共12条线程
for pagenum in range(3):
t = threading.Thread(target=findip, args=(type + 1, pagenum + 1, targeturl, path))
threads.append(t)
print('开始爬取代理ip')
for s in threads: # 开启多线程爬取
s.start()
for e in threads: # 等待所有线程结束
e.join()
print('爬取完成')
end = datetime.datetime.now() # 结束时间
diff = gettimediff(start, end) # 计算耗时
ips = read(path) # 读取爬到的ip数量
print('一共爬取代理ip: %s 个,共耗时: %s \n' % (len(ips), diff)) # -------------------------------------------------------启动-----------------------------------------------------------
if __name__ == '__main__':
path = 'ip.txt' # 存放爬取ip的文档path
targeturl = 'http://www.cnblogs.com/TurboWay/' # 验证ip有效性的指定url
getip(targeturl, path)

利用Python爬取免费代理IP的更多相关文章

  1. 极简代理IP爬取代码——Python爬取免费代理IP

    这两日又捡起了许久不碰的爬虫知识,原因是亲友在朋友圈拉人投票,点进去一看发现不用登陆或注册,觉得并不复杂,就一时技痒搞一搞,看看自己的知识都忘到啥样了. 分析一看,其实就是个post请求,需要的信息都 ...

  2. python爬取免费优质IP归属地查询接口

    python爬取免费优质IP归属地查询接口 具体不表,我今天要做的工作就是: 需要将数据库中大量ip查询出起归属地 刚开始感觉好简单啊,毕竟只需要从百度找个免费接口然后来个python脚本跑一晚上就o ...

  3. 第二篇 - python爬取免费代理

    代理的作用参考https://wenda.so.com/q/1361531401066511?src=140 免费代理很多,但也有很多不可用,所以我们可以用程序对其进行筛选.以能否访问百度为例. 1. ...

  4. golang爬取免费代理IP

    golang爬取免费的代理IP,并验证代理IP是否可用 这里选择爬取西刺的免费代理Ip,并且只爬取了一页,爬取的时候不设置useAgent西刺不会给你数据,西刺也做反爬虫处理了,所以小心你的IP被封掉 ...

  5. 简单爬虫-爬取免费代理ip

    环境:python3.6 主要用到模块:requests,PyQuery 代码比较简单,不做过多解释了 #!usr/bin/python # -*- coding: utf-8 -*- import ...

  6. PHP简单爬虫 爬取免费代理ip 一万条

    目标站:http://www.xicidaili.com/ 代码: <?php require 'lib/phpQuery.php'; require 'lib/QueryList.php'; ...

  7. 利用python爬取58同城简历数据

    利用python爬取58同城简历数据 利用python爬取58同城简历数据 最近接到一个工作,需要获取58同城上面的简历信息(http://gz.58.com/qzyewu/).最开始想到是用pyth ...

  8. 利用python爬取城市公交站点

    利用python爬取城市公交站点 页面分析 https://guiyang.8684.cn/line1 爬虫 我们利用requests请求,利用BeautifulSoup来解析,获取我们的站点数据.得 ...

  9. 利用Python爬取可用的代理IP

    前言 就以最近发现的一个免费代理IP网站为例:http://www.xicidaili.com/nn/.在使用的时候发现很多IP都用不了. 所以用Python写了个脚本,该脚本可以把能用的代理IP检测 ...

  10. 利用Python爬取豆瓣电影

    目标:使用Python爬取豆瓣电影并保存MongoDB数据库中 我们先来看一下通过浏览器的方式来筛选某些特定的电影: 我们把URL来复制出来分析分析: https://movie.douban.com ...

随机推荐

  1. 官宣 | Hugging Face 中文博客正式发布!

    作者:Tiezhen.Adina.Luke Hugging Face 的中国社区成立已经有五个月之久,我们也非常高兴的看到 Hugging Face 相关的中文内容在各个平台广受好评,我们也注意到,H ...

  2. 实例化对象 A a = new A();

    "new" 在Java中代表实例化的意思, A a = new A()代表实例化了一个对象a, 这个对象a属于A类. 可以认为A是一个抽象概念, 对象a是一个实体(存储于内存), ...

  3. 微擎删除分类无法删除解决-select in效率低解决办法

    今天朋友微擎后台微网站里的分类要删除,可是怎么删除也不能删除,同样的系统另一套却可以迅速删除. 后来查询到是查询语句的问题,朋友的平台用户量太大,数据太大,用了以下语句,造成效率太低: SELECT ...

  4. OData WebAPI实践-OData与EDM

    本文属于 OData 系列 引言 在 OData 中,EDM(Entity Data Model) 代表"实体数据模型",它是一种用于表示 Web API 中的结构化数据的格式.E ...

  5. python库Munch的使用记录

    开头 日常操作字典发现发现并不是很便利,特别是需要用很多 get('xxx','-') 的使用,就觉得很烦,偶然看到Kuls大佬公众号发布的一篇技术文有对 python munch库的使用, 使得字典 ...

  6. 2022-10-08:以下go语言代码输出什么?A、0 0;B、0 4;C:4 0;D:4 4。 package main const s = “Go101.org“ // len(s) == 9

    2022-10-08:以下go语言代码输出什么?A.0 0:B.0 4:C:4 0:D:4 4. package main const s = "Go101.org" // len ...

  7. 2020-09-18:LRU手撸,说下时间复杂度和空间复杂度。

    福哥答案2020-09-18: 方法:哈希表 + 双向链表.时间复杂度:对于 put 和 get 都是 O(1).空间复杂度:O(capacity),因为哈希表和双向链表最多存储 capacity+1 ...

  8. 2021-10-30:有效的字母异位词。给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位

    2021-10-30:有效的字母异位词.给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词.注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位 ...

  9. 将远程oracle数据库导入到本地

    一.切换用户 先从普通用户 切换到root (有些时候会因为无权限直接执行 su - oracle 会被拒绝) fssa@jzsql.sn.com:/home/fssa>su - 从当前用户切换 ...

  10. Python连接es笔记一之连接与查询es

    本文首发于公众号:Hunter后端 原文链接:Python连接es笔记一之连接与查询es 有几种方式在 Python 中配置与 es 的连接,最简单最有用的方法就是定义一个默认的连接,如果系统不是需要 ...