简述
本篇使用简单的爬虫程序来爬取免费 ip 网站的 ip 信息并生成 JSON 文档, 存储可用的 ip 地址, 写其它爬取项目的时候可以从生成的 JSON 文档中提取 ip 地址使用, 为了确保使用的 ip 地址的有效性, 建议对 JSON 文档中的 ip 现爬现用, 并且在爬取时对 ip 有效性的时间进行筛选, 只爬取时长较长, 可用的 ip 地址存储.
实现
使用平台 https://www.xicidaili.com/nn / 来作为数据源, 通过对 http://www.baidu.com / 的相应来判断 ip 的可使用性. 引用 lxml 模块来对网页数据进行提取, 当然也可以使用 re 模块来进行匹配提取, 这里只使用 lxml 模块对数据进行提取.
访问 https://www.xicidaili.com/nn / 数据源, 并且启动 Fiddler 对浏览器数据进行监听, 我这里浏览器采用的是 Proxy SwitchyOmega 插件来配合 Fiddler 进行使用, 在 Fiddler 找到 / nn/* 数据查看 User-Agent 信息并复制下来作为我们访问的头文件. 如图:
引入模块
- import requests
- from lxml import etree
- import time
- import JSON
获取所有数据
- def get_all_proxy(page):
- url = 'https://www.xicidaili.com/nn/%s'%page
- headers = {
- 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) ApplewebKit/537.36 (Khtml, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
- }
- response = requests.get(url, headers=headers)
- html_ele = etree.HTML(response.text)
- ip_eles = html_ele.xpath('//table[@id="ip_list"]/tr/td[2]/text()')
- port_ele = html_ele.xpath('//table[@id="ip_list"]/tr/td[3]/text()')
- print(ip_eles)
- proxy_list = []
- for i in range(0,len(ip_eles)):
- check_all_proxy(ip_eles[i],port_ele[i])
- return proxy_list
对数据进行筛选:
- def check_all_proxy(host,port):
- type = 'http'
- proxies = {}
- proxy_str = "%s://@%s:%s" % (type, host, port)
- valid_proxy_list = []
- url = 'http://www.baidu.com/'
- proxy_dict = {
- 'http': proxy_str,
- 'https': proxy_str
- }
- try:
- start_time = time.time()
- response = requests.get(url, proxies=proxy_dict, timeout=5)
- if response.status_code == 200:
- end_time = time.time()
- print('代理可用:' + proxy_str)
- print('耗时:' + str(end_time - start_time))
- proxies['type'] = type
- proxies['host'] = host
- proxies['port'] = port
- proxiesJson = JSON.dumps(proxies)
- with open('verified_y.json', 'a+') as f:
- f.write(proxiesJson + '\n')
- print("已写入:%s" % proxy_str)
- valid_proxy_list.append(proxy_str)
- else:
- print('代理超时')
- except:
- print('代理不可用 --------------->'+proxy_str)
运行程序:
- if __name__ == '__main__':
- for i in range(1,11): #选取前十页数据使用
- proxy_list = get_all_proxy(i)
- time.sleep(20)
- print(valid_proxy_list)
生成的 JSON 文件:
来源: http://www.bubuko.com/infodetail-3416860.html