
- 性能指标
- 吞吐量、最大并发连接数、丢包率等
- 外文名
- Proxy Server
- 作 用
- 充当防火墙、节省IP开销等
- 中文名
- 代理服务器
- 功 能
- 代理网络用户去取得网络信息
- 属 性
- 一种计算机应用软件
-
2022-01-18 09:42:52
概述
用爬虫时,大部分网站都有一定的反爬措施,有些网站会限制每个 IP 的访问速度或访问次数,超出了它的限制你的 IP 就会被封掉。对于访问速度的处理比较简单,只要间隔一段时间爬取一次就行了,避免频繁访问;而对于访问次数,就需要使用代理 IP 来帮忙了,使用多个代理 IP 轮换着去访问目标网址可以有效地解决问题。
目前网上有很多的代理服务网站提供代理服务,也提供一些免费的代理,但可用性较差,如果需求较高可以购买付费代理,可用性较好。
因此我们可以自己构建代理池,从各种代理服务网站中获取代理 IP,并检测其可用性(使用一个稳定的网址来检测,最好是自己将要爬取的网站),再保存到数据库中,需要使用的时候再调用。
提供免费代理的网站
本次使用的案例是小幻代理
代码
导包
import loguru, requests, random, time # 发送请求,记录日志,等 from lxml import etree # 分析数据 from concurrent.futures import ThreadPoolExecutor # 线程池
网站页面的url
由于小幻代理的每个页面的url没有规律,所以需要一一获取
def get_url(): # 得到存放ip地址的网页 print("正在获取ip池", ",不要着急!") for i in range(random.randint(10, 20)): # 爬取随机页数 time.sleep(1) if i == 0: url = "https://ip.ihuan.me/" else: url = url_list[-1] try: resp = requests.get(url=url, headers=headers_test, timeout=10) except Exception as e: print(e) break html = etree.HTML(resp.text) ul = html.xpath('//ul[@class="pagination"]') ul_num = html.xpath('//ul[@class="pagination"]/li') for j in range(len(ul_num)): if j != 0 and j != len(ul_num) - 1: a = ul[0].xpath(f"./li[{j}+1]/a/@href")[0] url_list.append("https://ip.ihuan.me/" + a) # 得到许多的代理ip网址 loguru.logger.info(f"over,{url}")
ip地址
def get_ip(): for i in url_list: time.sleep(1) resp = requests.get(url=i, headers=headers) html = etree.HTML(resp.text) td = html.xpath("//tbody/tr") for i in td: ip = i.xpath("./td[1]//text()")[0] # 地址 pt = i.xpath("./td[2]//text()")[0] # 端口 tp = "http" if i.xpath("./td[5]//text()")[0] == "不支持" else "https" # 访问类型 ip_list.append({"type": tp, "proxy": f"{ip}:{pt}"}) loguru.logger.info("ip地址获取完成")
检测
def test_ip(ip): proxy_test = { "http": f"{ip}", "https": f"{ip}" # 注意:如果请求的ip是https类型的,但代理的ip是只支持http的,那么还是使用本机的ip,如果请求的ip是http类型的,那么代理的ip一定要是http的,前面不能写成https,否则使用本机IP地址 } resp = requests.get(url=url_test, headers=headers, proxies=proxy_test, timeout=6) if resp.json()["origin"] == ip.split(":")[0]: ip = {"type": url.strip(":")[0], "proxy": ip} # 格式化ip,便于后期处理,是的其有http/https标识 temp_ip.append(ip) # 符合条件的添加,不符合条件的抛弃
整理
def set_ip(url) -> "动态构建ip池": # 要传入需要爬取网页的url try: f = open('./app/ip.txt', "r") for j in eval(f.read()): temp_ip.append(j) f.close() except Exception as e: print("没有ip,正在构造ip池,请稍等") if not temp_ip: # 判断是否有ip地址 print("没有ip地址,正在获取") get_url() else: for i in temp_ip: ip_list.append(i) # 将已有的ip添加到测试ip中 temp_ip.clear() get_ip() # 得到大量ip地址 with open('./app/ip.txt', "w") as file: file.write(ip_list) ip_able = list(set(j["proxy"] for j in ip_list if j["type"] == url.split(":")[0])) # 存放符合要求的ip字符串,同时利用字典去重 url_test = "http://httpbin.org/ip" if url.split(":")[0] == "http" else "" # 测试ip地址是否有用 def test_ip(ip): proxy_test = { "http": f"{ip}", "https": f"{ip}" # 注意:如果请求的ip是https类型的,但代理的ip是只支持http的,那么还是使用本机的ip,如果请求的ip是http类型的,那么代理的ip一定要是http的,前面不能写成https,否则使用本机IP地址 } resp = requests.get(url=url_test, headers=headers, proxies=proxy_test, timeout=6) if resp.json()["origin"] == ip.split(":")[0]: ip = {"type": url.strip(":")[0], "proxy": ip} # 格式化ip,便于后期处理,是的其有http/https标识 temp_ip.append(ip) # 符合条件的添加,不符合条件的抛弃 with ThreadPoolExecutor(50) as pool: # 使用多线程测试 pool.map(test_ip, ip_able) pool.join() print("测试完毕") if temp_ip: i = random.choice(temp_ip) proxy = { "http": f"{i['proxy']}", "https": f"{i['proxy']}" } return proxy else: set_ip(url=url)
必要参数
# 参数 headers = { 'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" } headers_test = { 'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36", "accept-encoding": "gzip, deflate, br", "cookie": "Hm_lvt_8ccd0ef22095c2eebfe4cd6187dea829=1642389014,1642412091", "Referer": "https://ip.ihuan.me/" } url_list, ip_list, temp_ip = ["https://ip.ihuan.me/"], [], [] # 存放url, 存放ip地址, 有用的ip地址
总代码
import loguru, requests, random, time from lxml import etree from concurrent.futures import ThreadPoolExecutor def get_url(): # 得到存放ip地址的网页 print("正在获取ip池", ",不要着急!") for i in range(random.randint(10, 20)): # 爬取随机页数 time.sleep(1) if i == 0: url = "https://ip.ihuan.me/" else: url = url_list[-1] try: resp = requests.get(url=url, headers=headers_test, timeout=10) except Exception as e: print(e) break html = etree.HTML(resp.text) ul = html.xpath('//ul[@class="pagination"]') ul_num = html.xpath('//ul[@class="pagination"]/li') for j in range(len(ul_num)): if j != 0 and j != len(ul_num) - 1: a = ul[0].xpath(f"./li[{j}+1]/a/@href")[0] url_list.append("https://ip.ihuan.me/" + a) # 得到许多的代理ip网址 loguru.logger.info(f"over,{url}") def get_ip(): for i in url_list: time.sleep(1) resp = requests.get(url=i, headers=headers) html = etree.HTML(resp.text) td = html.xpath("//tbody/tr") for i in td: ip = i.xpath("./td[1]//text()")[0] # 地址 pt = i.xpath("./td[2]//text()")[0] # 端口 tp = "http" if i.xpath("./td[5]//text()")[0] == "不支持" else "https" # 访问类型 ip_list.append({"type": tp, "proxy": f"{ip}:{pt}"}) loguru.logger.info("ip地址获取完成") def set_ip(url) -> "动态构建ip池": # 要传入需要爬取网页的url try: f = open('./app/ip.txt', "r") for j in eval(f.read()): temp_ip.append(j) f.close() except Exception as e: print("没有ip,正在构造ip池,请稍等") if not temp_ip: # 判断是否有ip地址 print("没有ip地址,正在获取") get_url() else: for i in temp_ip: ip_list.append(i) # 将已有的ip添加到测试ip中 temp_ip.clear() get_ip() # 得到大量ip地址 with open('./app/ip.txt', "w") as file: file.write(ip_list) ip_able = list(set(j["proxy"] for j in ip_list if j["type"] == url.split(":")[0])) # 存放符合要求的ip字符串,同时利用集合去重 url_test = "http://httpbin.org/ip" if url.split(":")[0] == "http" else "" # 测试ip地址是否有用 def test_ip(ip): proxy_test = { "http": f"{ip}", "https": f"{ip}" # 注意:如果请求的ip是https类型的,但代理的ip是只支持http的,那么还是使用本机的ip,如果请求的ip是http类型的,那么代理的ip一定要是http的,前面不能写成https,否则使用本机IP地址 } resp = requests.get(url=url_test, headers=headers, proxies=proxy_test, timeout=6) if resp.json()["origin"] == ip.split(":")[0]: ip = {"type": url.strip(":")[0], "proxy": ip} # 格式化ip,便于后期处理,是的其有http/https标识 temp_ip.append(ip) # 符合条件的添加,不符合条件的抛弃 with ThreadPoolExecutor(50) as pool: # 使用多线程测试 pool.map(test_ip, ip_able) pool.join() print("测试完毕") if temp_ip: i = random.choice(temp_ip) proxy = { "http": f"{i['proxy']}", "https": f"{i['proxy']}" } return proxy else: set_ip(url=url) # 参数 headers = { 'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" } headers_test = { 'User-Agent': "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 96.0.4664 .93 Safari / 537.36", "accept-encoding": "gzip, deflate, br", "cookie": "Hm_lvt_8ccd0ef22095c2eebfe4cd6187dea829=1642389014,1642412091", "Referer": "https://ip.ihuan.me/" } url_list, ip_list, temp_ip = ["https://ip.ihuan.me/"], [], [] # 存放url, 存放ip地址, 有用的ip地址 if __name__ == '__main__': proxy = set_ip(url="https://www.baidu.com") # 得到代理ip print(proxy)
总结
如果安装了数据库的话,可以使用数据库存储得到的ip,代码中使用的是本地的文件存储数据,同时,要尽量避免本机ip被封
更多相关内容 -
Pandas一键爬取解析代理IP与代理IP池的维护
2021-07-04 00:16:51当然相对爬取免费的代理IP自己搭建代理IP池,本人更推荐大家直接购买付费的代理IP,相对而言稳定而且省心好用。 那么对于穷人而言,为了训练一下自己的技术并省下几块钱,咱们还是决定自己搭建一个玩玩。 要搭建一个...大家好,我是小小明,今天我们计划搭建一个代理Ip池。当然相对爬取免费的代理IP自己搭建代理IP池,本人更推荐大家直接购买付费的代理IP,相对而言稳定而且省心好用。
那么对于穷人而言,为了训练一下自己的技术并省下几块钱,咱们还是决定自己搭建一个玩玩。
要搭建一个代理ip池,我的思路:
- 爬虫定期爬取代理IP,验证代理iP有效性,有效则存入Redis数据库
- 一个线程或进程定期检查代理ip池的有效性,无效则从中删除
代理IP的爬取与解析
下面,首先去选择几个免费代理ip的网址去爬一下,这里我选择了快代理。
快代理提供了高匿代理和普通代理两个页面供爬取,网址是:
爬取高匿测试一下:
import requests import pandas as pd headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36' } i = 1 url = f'https://www.kuaidaili.com/free/inha/{i}/' r = requests.get(url, headers=headers) r.encoding = 'u8' ip_df, = pd.read_html(r.text) ip_df
代理IP爬了,但是是否真的能用呢?
代理IP的校验
我们需要验证一下,有个不错的测试网站是httpbin.org,我们可以通过它来读取自己的ip地址:
r = requests.get(f"http://httpbin.org/ip") r.json()
结果大致形式:
{'origin': '116.xx.xx.xxx'}
然后以如下形式访问代理ip:
r = requests.get(f"http://httpbin.org/ip", proxies={'http': "175.42.158.226:9999"}) r.json()
若抛出异常:
说明代理失效。
在我们的机器有公网IP时,我们也可以搭建自己的服务器用于校验代理IP有效性,flask代码:
from flask import * app = Flask(__name__) @app.route('/') def index(): return request.remote_addr if __name__ == '__main__': app.run(host="0.0.0.0", port=8088)
基于此我们可以写一个校验代理IP的方法:
def proxie_ip_validity_check(proxie_ip, proxie_type='http', timeout=1): try: r = requests.get(f"{proxie_type}://httpbin.org/ip", headers=headers, proxies={proxie_type: proxie_ip}, timeout=timeout) if r.status_code == 200: return True return False except Exception as e: return False
经过我个人测试,高匿代理似乎没有一个是可以用的,所以这次我们只爬取普通代理ip。
批量爬取普通代理ip
设置超时时间为2秒,取7页数据:
import requests import pandas as pd headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36' } http_ip_pool = [] https_ip_pool = [] for page in range(1, 8): print("当前爬取页面数:", page) url = f'https://www.kuaidaili.com/free/intr/{page}' r = requests.get(url, headers=headers) r.encoding = 'u8' ip_df, = pd.read_html(r.text) for ip, port, proxie_type in ip_df[["IP", "PORT", "类型"]].values: pool = http_ip_pool if proxie_type.lower() == 'http' else https_ip_pool proxie_ip = f"{ip}:{port}" if proxie_ip_validity_check(proxie_ip, proxie_type.lower(), 2): pool.append(proxie_ip) len(http_ip_pool), len(https_ip_pool)
经测试爬到26个有效的代理ip,全部都是http类型:
写入到Redis服务器
为了方便其他爬虫程序使用,我们将爬到的代理IP写入到Redis数据库中。
首先需要安装Redis,下载地址:https://github.com/MicrosoftArchive/redis/releases
我的是Windows平台选择了:https://github.com/microsoftarchive/redis/releases/download/win-3.0.504/Redis-x64-3.0.504.zip
解压后直接双击redis-server.exe即可启动Redis服务器:
安装让Python操作redis的库:
pip install redis
基本使用:
import redis r = redis.Redis(host='192.168.3.31', port=6379, db=0) r.set('name', 'zhangsan') # 添加 print(r.get('name'))
b'zhangsan'
考虑将代理IP存入Redis的set集合中,因为可以自动去重,测试一下:
r.sadd("proxie_ip", "ip1", "ip2") r.sadd("proxie_ip", "ip2", "ip3") r.smembers("proxie_ip")
{b'ip1', b'ip2', b'ip3'}
于是我们可以通过以下命令一次性存入Redis中:
if len(http_ip_pool)>0: r.sadd("proxie_ip_http", *http_ip_pool) if len(https_ip_pool)>0: r.sadd("proxie_ip_https", *https_ip_pool)
存入Redis数据库后,Redis就已经相当于一个代理IP池,下面我们另外启动一个尝试,常识使用这些代理IP:
从代理Ip池中获取代理IP并使用
读取代理IP:
import redis with redis.Redis(host='192.168.3.31', port=6379, db=0) as r: http_ip_bytes = r.smembers("proxie_ip_http") http_ip_pool = list(map(bytes.decode, http_ip_bytes)) http_ip_pool
['139.9.25.69:3128', '119.3.235.101:3128', '122.51.207.244:8888', '106.58.191.24:8888', '222.74.202.229:9999', '47.111.71.29:8081', '222.74.202.229:80', '222.74.202.244:80', '106.58.191.218:8888', '222.74.202.229:8080']
然后可以拿来模拟爬百度:
import requests headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36' } for ip in http_ip_pool: try: r = requests.get(f"http://www.baidu.com/", headers=headers, proxies={'http': ip}, timeout=1) print(r.status_code) except Exception as e: print(e)
HTTPConnectionPool(host='139.9.25.69', port=3128): Max retries exceeded with url: http://www.baidu.com/ (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x0000028D6A993248>, 'Connection to 139.9.25.69 timed out. (connect timeout=1)')) 200 200 HTTPConnectionPool(host='106.58.191.24', port=8888): Max retries exceeded with url: http://www.baidu.com/ (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x0000028D6B59C2C8>, 'Connection to 106.58.191.24 timed out. (connect timeout=1)')) 200 HTTPConnectionPool(host='47.111.71.29', port=8081): Max retries exceeded with url: http://www.baidu.com/ (Caused by ProxyError('Cannot connect to proxy.', RemoteDisconnected('Remote end closed connection without response'))) 200 200 HTTPConnectionPool(host='106.58.191.218', port=8888): Max retries exceeded with url: http://www.baidu.com/ (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x0000028D6A9C2F88>, 'Connection to 106.58.191.218 timed out. (connect timeout=1)')) 200
可以看到只有一半的代理IP能在指定时间内成功访问百度,说明免费的代理IP就是不如收费的稳定。
定期爬取并清除失效的代理IP
只要再完成这部分,我们的代理IP池就能够初见雏形,冲!
最终完成代码:
import requests import pandas as pd import redis from threading import Timer import time headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36' } def proxie_ip_validity_check(proxie_ip, proxie_type='http', timeout=2): try: r = requests.get(f"{proxie_type}://httpbin.org/ip", proxies={proxie_type: proxie_ip}, timeout=timeout) if r.status_code == 200: return True return False except: return False redis_conn = redis.Redis(host='192.168.3.31', port=6379) def crawl_proxy_ip2redis(): for page in range(1, 20): print("当前爬取页面:", page) url = f'https://www.kuaidaili.com/free/intr/{page}' r = requests.get(url, headers=headers) r.encoding = 'u8' ip_df, = pd.read_html(r.text) for ip, port, proxie_type in ip_df[["IP", "PORT", "类型"]].values: proxie_ip = f"{ip}:{port}" proxie_type = proxie_type.lower() if proxie_ip_validity_check(proxie_ip, proxie_type, 2): redis_conn.sadd(f"proxie_ip_{proxie_type}", proxie_ip) def get_proxy_ip_pool(proxie_type='http'): http_ip_bytes = redis_conn.smembers(f"proxie_ip_{proxie_type}") http_ip_pool = list(map(bytes.decode, http_ip_bytes)) return http_ip_pool def clear_invalid_proxie_ip(): print("开始清空失效代理ip:") for proxie_type in ['http', 'https']: for ip in get_proxy_ip_pool(proxie_type): if not proxie_ip_validity_check(ip, proxie_type, 2): print(proxie_type, ip, "失效") redis_conn.srem(f"proxie_ip_{proxie_type}", ip) crawl_proxy_ip2redis() while True: # 5分钟后清空一次失效的代理ip Timer(5 * 60, clear_invalid_proxie_ip, ()).start() # 10分钟后下载一次代理ip Timer(10 * 60, crawl_proxy_ip2redis, ()).start() # 每隔10分钟一个周期 time.sleep(10 * 60)
目前测试,这个Redis代理IP池还算好使,作为一个雏形勉强能用。
可以通过Redis图形化工具查看代理IP池的存储情况:
我使用的工具叫Redis Desktop Manager,可以百度下载。
目前我个人还算满意。
总结
通过本文讲解了:
- pandas超简代码带请求头解析表格
- 查看访问IP的方法
- 搭建简易检验代理Ip的网站
- Redis数据库的基本操作
- 代理ip在request库中的使用方法
- Timer定时器的使用
- Redis 图形化工具的使用介绍
我是小小明,希望你有所收获。
-
C# webbrowser控件设置代理IP访问网站
2014-10-15 16:57:49C#:webbrowser控件设置代理IP访问网站 -
selenium使用代理IP
2022-03-03 12:43:23python爬虫使用代理IP实战一、申请代理IP
如果一个用户对某个网站多次的访问,有可能会被识别为爬虫,因而限制其客户端 ip 的访问,对于一些比较正规的网站,反爬系统很强,最容易出现这种情况,所以有时候有必要使用代理IP,我一般选择使用随机动态的代理ip,这样可以保证每次访问时随机的一个用户而不是一个固定的用户。
话不多说,注册IPIDEA进去,注册就送免费的100M流量,有特殊需求不够再买:
http://www.ipidea.net/?utm-source=gejing&utm-keyword=?gejing
生成API:
点击生成链接
复制链接包存起来,等会用。
二、在selenium使用代理IP实战(一)
设置代理基本格式:
import requests proxies = { 'http': 'http://222.89.32.159:21079', 'https': 'http://222.89.32.159:21079' } headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" } res = requests.get(url=urls,headers=headers,proxies=proxies)
我想了半天没想好到底哪些网站反爬强,所以我就随便找一个网站来测试了,你可以再去尝试逛一下自己学校的教务管理系统,12360,facebook等…
目标网址:
https://www.taobao.com/
所以定位就很容易:driver.find_element_by_name('q')
之前写过一次使用代理玩爬虫,是requests模块,但是作为个人,我越往后面学,发现selenium用得反而越来越多,requests被逐渐抛弃一般,所以这里补充一个selenium添加代理。
方式很简单:
ops.add_argument('--proxy-server=http://%s' % a) #添加代理
注意这里的a格式为:ip:port
注意: 使用代理ip需要安装模块selenium-wire:
pip install selenium-wire
你应该是:
from seleniumwire import webdriver
而不是:
from selenium import webdriver
比如在X宝搜索:XX手机
完整代码:
from selenium import webdriver from fake_useragent import UserAgent from selenium.webdriver.chrome.options import Options headers = {'User-Agent': UserAgent().random} ops = Options() driver = webdriver.Chrome(r'D:\360安全浏览器下载\chromedriver.exe') api_url = '让你复制的代理api链接' driver.get(api_url) a = driver.find_element_by_xpath('/html/body/pre').text # 获取代理 ops.add_argument('--proxy-server=http://%s' % a) #添加代理 driver.delete_all_cookies() #清楚cookies driver.get('https://www.taobao.com/') driver.find_element_by_name('q').send_keys('华为手机')
接下来是点击按钮:
确定点击的地方元素,然后使用click点击即可:from selenium.webdriver import ActionChains b= driver.find_element_by_class_name('search-button') #定位搜索 ActionChains(driver).click(b).perform()
可能是触发了反扒机制吗?需要登录,我也不知道我的X宝账号密码,随便演示输入一下…剩下的自己操作
这里是账号密码分析:
所以定位账号密码如下,账号我设置的输入:chuanchuan,密码设置的输入:123456 瞎编的,具体根据你的实际账号来操作,我就不讲下去了,就是定位定位点点点driver.find_element_by_name('fm-login-id').send_keys('chuanchuan') # 输入账号 driver.find_element_by_name('fm-login-password').send_keys('123456') # 输入密码
效果如下:
三、在selenium使用代理IP实战(二)
注意: 用代理爬外wang需要国外环境,为了演示我不得不买了一个国外环境测试,请看:国外环境服务器
比如:https://www.facebook.com/
分析账号密码登录:
代码为:
from fake_useragent import UserAgent import requests from selenium import webdriver from selenium.webdriver import ChromeOptions headers = {'User-Agent': UserAgent().random} api_url = '复制你的api' res = requests.post(api_url, headers=headers, verify=True) PROXY = res.text print(PROXY) ops = ChromeOptions() ops.add_argument('--proxy-server=%s' % PROXY) # 添加代理 driver = webdriver.Chrome(r'D:\360安全浏览器下载\chromedriver.exe', chrome_options=ops) driver.get("https://m.facebook.com/") driver.find_element_by_name('email').send_keys("你的账号") driver.find_element_by_name('pass').send_keys('你的密码') # 按钮 btnSubmit = driver.find_element_by_name('login') btnSubmit.click()
效果如下:
我的账号被封了,后续操作不继续演示,可以根据我讲的selenium知识点自行操作,无非就是点点点定位定位保存保存。
三、selenium单个元素定位实战复习
3.1 定位填写
以微软搜索引擎为例:
https://cn.bing.com/?mkt=zh-CN
分析:
所以:
from selenium import webdriver driver = webdriver.Chrome(r'D:\360安全浏览器下载\chromedriver.exe') driver.get('https://cn.bing.com/?mkt=zh-CN') driver.find_element_by_name('q').send_keys('川川菜鸟')
如下:
你也可以如下两种方式:driver.find_element_by_id('sb_form_q').send_keys('川川菜鸟')
driver.find_element_by_class_name('sb_form_q').send_keys('川川菜鸟')
send_keys函数就是填写信息的意思。
3.2 点击搜索
分析:id或者class
b=driver.find_element_by_id('search_icon') ActionChains(driver).click(b).perform()
如下:
上面是id定位,把class定位也写一下:b = driver.find_element_by_class_name('search') ActionChains(driver).click(b).perform()
有趣的是,定位class的时候是:search而不是search icon tooltip,个人认为可能是因为这个空格的原因,还好有爬虫经验,不然死卡在这个定位不对了。
3.3 完整代码
代理api请替换为你的,按照我的的方法去申请:
# coding=gbk """ 作者:川川 公众号:玩转大数据 @时间 : 2022/3/3 17:11 群:428335755 """ from selenium import webdriver from selenium.webdriver import ActionChains driver = webdriver.Chrome(r'D:\360安全浏览器下载\chromedriver.exe') driver.get('https://cn.bing.com/?mkt=zh-CN') # driver.find_element_by_name('q').send_keys('川川菜鸟') # driver.find_element_by_id('sb_form_q').send_keys('川川菜鸟') driver.find_element_by_class_name('sb_form_q').send_keys('川川菜鸟') # b=driver.find_element_by_id('search_icon') b = driver.find_element_by_class_name('search') ActionChains(driver).click(b).perform()
-
python3之爬虫代理IP的使用+建立代理IP池
2021-01-10 13:49:56爬虫代理IP的使用+建立代理IP池代理IP的使用建立代理IP池完整代码 代理IP的使用 先了解一下百度百科定义的IP 为什么要使用代理IP? 反爬(反网络爬虫) 示例: 测试网址 http://httpbin.org/get 浏览器先...代理
IP
的使用http://httpbin.org/get
-
用浏览器先访问测试网址下看看
-
再用我们写的代码简单请求一下网页看看
import requests url='http://httpbin.org/get' html=requests.get(url=url).text print(html) """ { "args": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "python-requests/2.23.0", "X-Amzn-Trace-Id": "Root=1-5ff704d4-3841771516040beb29f6066f" }, "origin": "1.192.244.128", "url": "http://httpbin.org/get" } """
疑惑???
“User-Agent”: “python-requests/2.23.0”
网站如何来判定是人类正常访问还是爬虫程序访问? —> 检查请求头!!!
我们是不是需要发送请求时重构一下User-Agent
???
添加headers
参数!!!那就使用
fake_useragent
模块
让它伪造一个出来再试试import requests from fake_useragent import UserAgent url='http://httpbin.org/get' headers={'User-Agent':UserAgent().random} html=requests.get(url=url,headers=headers).text print(html) """ { "args": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0.6", "X-Amzn-Trace-Id": "Root=1-5ff7a4de-05f8d7bf49dfe85e3be31d79" }, "origin": "1.192.244.128", "url": "http://httpbin.org/get" } """
“User-Agent”: “Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0.6”
添加好
headers
的参数就可以了吗?
这还不行吗!!!
一些网站不但检测 请求头
一个IP
异常请求频繁(访问频率过多) 封禁?“origin”: “1.192.244.128”
这是一项就是博主的
IP
, 我怎么确定这就是我的IP
呢?
查询一下:果真如此
找个免费的代理IP
来包装下- 定义
代替你原来的IP
地址去对接网络的IP
地址 - 作用
隐藏自身真实IP
, 避免被封 - 获取代理
IP
网站
快代理、全网代理、代理精灵、… …
这次加上代理
IP
再去请求下import requests from fake_useragent import UserAgent url='http://httpbin.org/get' headers={'User-Agent':UserAgent().random} # 参数类型 # proxies # proxies = {'协议': '协议://IP:端口号'} proxies = { 'http': 'http://{}'.format('8.129.28.247:8888'), 'https': 'https://{}'.format('8.129.28.247:8888'), } html=requests.get(url=url,headers=headers,proxies=proxies).text print(html) """ { "args": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36", "X-Amzn-Trace-Id": "Root=1-5ff7a71d-10b181340f8dc04f7514dfba" }, "origin": "8.129.28.247", "url": "http://httpbin.org/get" } """
“origin”: “8.129.28.247”
这次和我们加入的
IP
一样, 而不是我们自己的IP
直接去请求了
但这一个够用吗?
别着急往下看啦~~~建立代理
IP
池构建一个
IP
池
每次让它随机提供一个来请求不就解决一个IP
请求频繁而导致封掉了
这样就达到我们想要的结果了- 定义一个测试函数
import requests from fake_useragent import UserAgent test_url = 'http://httpbin.org/get' headers = {'User-Agent': UserAgent().random} # 参数 IP 地址 def test_proxy(proxy): '''测试代理IP是否可用''' proxies = { 'http': 'http://{}'.format(proxy), 'https': 'https://{}'.format(proxy), } # 参数类型 # proxies # proxies = {'协议': '协议://IP:端口号'} # timeout 超时设置 网页响应时间3秒 超过时间会抛出异常 try: resp = requests.get(url=test_url, proxies=proxies, headers=headers, timeout=3) # 查看状态码 if resp.status_code == 200: print(proxy, '\033[31m可用\033[0m') else: print(proxy, '不可用') except Exception as e: print(proxy, '不可用')
get
一下HTTP状态码完整代码
# 建立属于自己的开放代理IP池 import requests import random import time from lxml import etree from fake_useragent import UserAgent class IpPool: def __init__(self): # 测试ip是否可用url self.test_url = 'http://httpbin.org/get' # 获取IP的 目标url self.url = 'https://www.89ip.cn/index_{}.html' self.headers = {'User-Agent': UserAgent().random} # 存储可用ip self.file = open('ip_pool.txt', 'wb') def get_html(self, url): '''获取页面''' html = requests.get(url=url, headers=self.headers).text return html def get_proxy(self, url): '''数据处理 获取ip 和端口''' html = self.get_html(url=url) # print(html) elemt = etree.HTML(html) ips_list = elemt.xpath('//table/tbody/tr/td[1]/text()') ports_list = elemt.xpath('//table/tbody/tr/td[2]/text()') for ip, port in zip(ips_list, ports_list): # 拼接ip与port proxy = ip.strip() + ":" + port.strip() # print(proxy) # 175.44.109.195:9999 self.test_proxy(proxy) def test_proxy(self, proxy): '''测试代理IP是否可用''' proxies = { 'http': 'http://{}'.format(proxy), 'https': 'https://{}'.format(proxy), } # 参数类型 # proxies # proxies = {'协议': '协议://IP:端口号'} # timeout 超时设置 网页响应时间3秒 超过时间会抛出异常 try: resp = requests.get(url=self.test_url, proxies=proxies, headers=self.headers, timeout=3) # 获取 状态码为200 if resp.status_code == 200: print(proxy, '\033[31m可用\033[0m') # 可以的IP 写入文本以便后续使用 self.file.write(proxy) else: print(proxy, '不可用') except Exception as e: print(proxy, '不可用') def crawl(self): '''执行函数''' # 快代理每页url 的区别 # https://www.kuaidaili.com/free/inha/1/ # https://www.kuaidaili.com/free/inha/2/ # ....... # 提供的免费ip太多 # 这里只获取前100页提供的免费代理IP测试 for i in range(1, 101): # 拼接完整的url page_url = self.url.format(i) # 注意抓取控制频率 time.sleep(random.randint(1, 4)) self.get_proxy(url=page_url) # 执行完毕关闭文本 self.file.close() if __name__ == '__main__': ip = IpPool() ip.crawl()
测试完这里博主的脸可能比较黑吧, 竟没几个可以用的!!!
由于提供的免费IP
可用的机率很小
想构建自己的IP
池的小伙伴, 可以去获取其它代理, 提供的免费代理IP
.这里给大家提供几个博主当时测试时可以使用的
IP
159.203.44.177:3128
203.202.245.62:80
8.210.88.234:3128
89.187.177.106:80
89.187.177.106:80
96.113.165.182:3128
IP
的响应速度根据你机器所在的地理位置不同而有差异作者:淮南子.
来源:CSDN
版权声明:本文为博主原创文章,原创不易,请尊重原创转载请附上博文链接!
-
-
国内ip代理软件有哪些?哪个代理ip软件好?
2022-03-23 17:50:39随着网络的快速发展,现在通过手机、电脑等智能设备实现网络互联是如此...那国内IP代理软件有哪些呢,哪个国内代理ip软件好用呢? 想要系统快速的学习黑客技术可以关(加)注(我)攻重(即可)号,白帽黑客训练营,里面有惊 -
Python搭建代理IP池(一)- 获取 IP
2019-10-13 21:57:41而对于访问次数,就需要使用代理 IP 来帮忙了,使用多个代理 IP 轮换着去访问目标网址可以有效地解决问题。 目前网上有很多的代理服务网站可以提供代理服务,也提供一些免费的代理,但可用性较差,如果需... -
搭建代理IP池
2021-07-30 20:46:38目录 爬取前的准备 爬取有IP内容 检查IP的可用性 ...通常来说,搭建代理IP池,就是爬取代理IP网站,然后做成一个IP的形式,最后在requests请求访问网站的时候proxies指定IP去访问。 爬取前的准备 有很多... -
《Python 黑科技》代理ip奇技淫巧
2022-01-15 19:15:43案例分享:浏览器设置代理ip、代理ip访问网页 -
Python爬虫之利用xpath爬取ip代理网站的代理ip
2021-12-15 22:58:57用xpath爬取ip代理网站,新手爬虫 -
爬虫日记-采集 快代理 免费 代理ip 并 清洗 ip 附源码gitee,可运行
2021-12-08 16:07:37title: 爬虫日记-采集 快代理 免费 代理ip 并 清洗 ip tags: ['requests','python','lxml','代理ip','proxy'] date: 2021-12-08 categories: "磨刀不误砍柴工" ... -
Python之爬虫 搭建代理ip池
2022-01-29 14:19:33文章目录前言一、User-...下面就开始来简单地介绍一下爬取免费的代理ip来搭建自己的代理ip池: 本次爬取免费ip代理的网址:http://www.ip3366.net/free/ 提示:以下是本篇文章正文内容,下面案例可供参考 一、User-Ag -
如何建立爬虫代理ip池
2019-04-10 09:08:20一、为什么需要建立爬虫代理ip池 二、如何建立一个爬虫代理ip池 原文地址:https://www.cnblogs.com/TurboWay/p/8172246.html 一、为什么需要建立爬虫代理ip池 在众多的网站防爬措施中,有一种是根据ip的访问... -
python爬虫 - 代理ip正确使用方法
2022-04-26 11:43:33主要内容:代理ip使用原理,怎么在自己的爬虫里设置代理ip,怎么知道代理ip是否生效,没生效的话哪里出了问题,个人使用的代理ip(付费)。 -
快排之万能代理IP接口设计
2021-12-10 15:48:48我们在《python脚本百度(SEO)快排--模拟点击最新核心源码》中提到对快排影响的重要因素之一就是IP,今天我们主要来说下如何设计一个万能的代理IP池接口?我们随便找几家做代理IP池的厂家,看看他们都是什么样的接口... -
简易代理IP池的搭建
2019-05-11 17:09:42简易代理IP池搭建 -
本地计算机如何使用代理服务器,自动设置代理ip
2021-06-23 21:47:51如何让网站不知道是你在请求它,就需要设置代理ip。但:代理网站是知道你的地址的哦。 已经学会了如何请求接口时,添加代理,那如何为本地结算机设置代理呢。 找到我们的代理ip,然后按照下面的操作进行。 目录 ... -
ProxyPool 爬虫代理IP池(分享)
2022-04-07 13:45:17GitHub - jhao104/proxy_pool: Python爬虫代理IP池(proxy pool)https://github.com/jhao104/proxy_pool/ProxyPool 爬虫代理IP池项目,主要功能为定时采集网上发布的免费代理验证入库,定时验证入库的代理保证代理的... -
每周一练:如何创建自己的Python爬虫代理IP池(免费IP)
2022-04-18 15:12:20学习Python爬虫的同学,都需要自己建造一个代理IP池(免费的),下面给大家分享代理IP池如何建池。 本项目爬取的是代理商提供的免费IP,如果需要稳定可靠的IP,建议购买他们官方的收费产品。 项目爬取代理IP商列表... -
scrapy设置代理ip(精简版)
2022-03-14 09:07:52在middlewares.py文件中,添加下面的代码。 import scrapy from scrapy import signals import random class ProxyMiddleware... #ip = random.choice(self.ip) request.meta['proxy'] = "http://"+"58.246.58.15 -
如何构建一个自己的代理ip池
2019-02-21 18:09:19这种时候,我们就需要一个代理ip池。 什么是代理ip池? 通俗地比喻一下,它就是一个池子,里面装了很多代理ip。它有如下的行为特征: 1.池子里的ip是有生命周期的,它们将被定期验证,其中失效的将被从池子里面... -
如何判断代理IP的匿名程度?
2021-12-15 10:58:06简单点说,代理ip根据安全和质量程度,被分为透明代理、普通代理跟高匿代理,使用透明代理被访服务器可以获取本机的真实ip。 使用普通代理虽然被访服务器无法获取本机真实ip,但是依旧知道本机使用了代理ip,只有高... -
爬取小舒代理免费代理IP,并验证IP是否有效
2021-03-05 14:36:17使用多线程+队列+正则匹配,对免费代理ip网站和查询自身ip网站(验证代理ip是否有效)发送请求,如果代理ip为有效,保存至本地txt文件中,建立自己的私人有效代理ip池。 代码: #!/usr/bin/env python # -*- coding:... -
Java语言HttpClient使用代理IP
2019-12-19 10:01:03在访问一个网站时,有时我们不想让对方获取到我们的真实IP,这种情况下,就可以使用代理IP进行访问。 1、maven依赖 <dependency> <groupId>org.apache.httpcomponents</groupId> <... -
python爬取代理IP并进行有效的IP测试
2020-10-07 16:38:02爬取代理IP及测试是否可用 很多人在爬虫时为了防止被封IP,所以就会去各大网站上查找免费的代理IP,由于不是每个IP地址都是有效的,如果要进去一个一个比对的话效率太低了,我也遇到了这种情况,所以就直接尝试了一... -
代理IP的主要用途和使用注意事项
2022-03-26 15:53:06使用代理IP容易出现的问题和解决办法。 -
【Python爬虫从入门到精通 · 4】:代理ip的了解和基本使用、查看代理ip的有效性(附源代码)
2022-03-13 21:57:10一、代理IP的了解和基本使用 1、代理IP 正向代理 反向代理 2、代理IP的分类 3、代理IP的基本使用 第一种用法:https 第二种用法:http 二、查看代理IP的有效性 1、查看自己的IP地址 2、在网上查找免费的... -
什么是代理ip池?
2022-04-08 17:48:09什么是代理ip池? 通俗地比喻一下,它就是一个池子,里面装了很多代理ip。它有如下的行为特征: 1.池子里的ip是有生命周期的,它们将被定期验证,其中失效的将被从池子里面剔除。 2.池子里的ip是有补充渠道的,会有... -
浅谈云函数的代理IP利用面
2022-01-03 13:41:30浅谈云函数的代理IP利用面 前言 本篇文章介绍如何通过 Serverless(云函数) 实现各种扫描器探测功能,以达到绕过态势感知、WAF等安全设备,增大蓝队研判人员溯源难度,实现封无可封,查无可查的效果。 什么是云函数... -
python爬虫代理ip
2022-01-10 11:08:49代理ip 爬虫去爬取网站数据的数据的时候,如果单位时间内爬取频次过高,或者其他的原因,被对方识别出来,ip可能会被封禁。这种情况下,通过使用代理ip来解决,作为反爬的策略。 代理ip匿名度: 透明的: 服务器...