获取一个代理
从免费代理的网站取一条数据
例如:
免费代理 - IP海
http://www.iphai.com/free/ng
60.12.89.218 33920 高匿 HTTPS 中国浙江嘉兴 4.14s 34分钟前
114.99.54.65 8118 高匿 HTTPS 中国安徽安庆 0.20s 34分钟前
47.110.130.152 8080 高匿 HTTPS 中国浙江杭州 0.08s 35分钟前
221.178.232.130 8080 高匿 HTTPS 中国江苏苏州 0.09s 35分钟前
110.86.136.92 9999 高匿 HTTPS 中国福建宁德 0.17s 35分钟前
49.73.113.215 9999 高匿 HTTPS 中国江苏苏州 0.11s 35分钟前
110.86.136.154 9999 高匿 HTTPS 中国福建宁德 0.16s 35分钟前
代理的用法
爬取演练
关注爬取的一个时间
import requests
proxies = {"https":"60.12.89.218:33920"}
s = """User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
"""
headers = {s.strip().split(":")[0].strip():s.strip().split(":")[1].strip()}
print(s)
print(headers)
url = "https://www.360kuai.com/903454ae58cf857f2?refer_scene=&scene=&sign=360_46b9a0ef&tj_url=903454ae58cf857f2&uid=c68892e973deb25ad6f3f6f99bea6d1b"
res = requests.get(url, headers=headers, proxies=proxies)
print(res)
print(res.status_code)
print(res.content)
例子
import requests
class Spider:
def __init__(self):
"""初始化"""
self.star_url = "https://www.xicidaili.com/nn/"
self.header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"}
def run(self):
"""开始爬数据"""
# 拿到页面url
html = self.parse_url(self.star_url)
print(html)
# 保存数据
self.save_html(html)
# 提取数据,ip,port,https
self.get_proxie_data(html)
def get_proxie_data(self, html):
import re
com = re.compile(r'<tr class="">(.*?)</tr>', re.DOTALL)
com2 = re.compile(r'<tr class="odd">(.*?)</tr>', re.DOTALL)
tr_list = com2.findall(html)
print(tr_list)
p_list = []
for tr in tr_list:
# print(tr)
# print('......')
td_com = re.compile(r'<td>(.*?)</td>')
tdres_list = td_com.findall(tr)
print(tdres_list)
# ['27.152.91.83', '9999', 'HTTP', '1分钟', '19-10-11 16:21']
ip, port, xy, *_ = tdres_list
proxies = {xy.lower():"{}://{}:{}".format(xy.lower(),ip,port)}
p_list.append(proxies)
print(proxies)
print(p_list)
break
def parse_url(self, url):
"""爬取数据"""
res = requests.get(url, headers=self.header)
return res.content.decode()
def save_html(self, html):
with open('a.html', 'w', encoding='utf8') as f:
f.write(html)
o = Spider()
o.run()