zoukankan      html  css  js  c++  java
  • 获取ip地址&&测试ip地址

    # request
    # 动态页面加载 Selenium
    # request
    # 响应类型为 json
    # import json

    # json.loads(str) # 将str转化为dict
    # json.dumps(dict) # 将dict转化为 str

    #获取ip地址开始
    import requests
    from fake_useragent import UserAgent #代理
    from lxml.etree import HTML #获取html
    import time,pickle #包
    #常见的几种用法
    res = requests.get(url)
    print(res.text)
    print(res.content)
    print(res.url)
    print(res.encoding)
    print(res.status_code)

    url = "https://www.kuaidaili.com/free/inha/%s/"
    #获取代理开始(让网站不认为你在爬取数据)
    ua = UserAgent()
    headers={
    "User-Agent":ua.random
    }
    #获取代理结束
    def getIP(url):
    res = requests.get(url,headers=headers)#获取某个网页,省的解码
    doc = HTML(res.text) #解析html
    ips = doc.xpath("//td[@data-title='IP']/text()") #获取数据
    ports = doc.xpath("//td[@data-title='PORT']/text()")
    arr = [ ip+":"+port for ip,port in zip(ips,ports)] #以数组的形式返回
    return arr
    IPS = [] #定义空数组放置ip
    for i in range(1,10): #十页 遍历
    time.sleep(1) #间隔时间
    arr = getIP(url%i) #调用函数内容
    print(arr) #提示信息可以实时看到爬取信息
    IPS+=arr #一页数组 ,而不是都加在一个数组中

    with open("快代理.txt",'wb') as f: #写入文件 wb二进制写入
    pickle.dump(IPS,f)
    #测试ip
    with open("快代理.txt", 'rb') as f:
    arr = pickle.load(f) #加载文件
    IPs = [] # 可用代理ip
    def test(ip):
    #测试可能出现情况
    proxie = {
    'http':'http://%s' % ip,
    'https': 'https://%s' % ip,
    }
    #异常提醒
    try:
    res = requests.get('https://www.baidu.com', proxies=proxie, timeout=10)
    print("Ok%s可用" % ip)
    IPs.append(ip) #将可用的ip放到数组IPs中
    except Exception:#否则
    print("error %s不可用" % ip)
    for ip in arr:
    test(ip)
    print("共有%s可用" % len(IPs))
    with open("ip.txt", "wb") as f: #二进制写入
    pickle.dump(IPs, f)
  • 相关阅读:
    Python(21):numpy数组模块
    ASP.NET(99):ASP.NET 内容管理系统CMS
    Python(20):Python常用模块sys、random、math
    Python(19):Python标准库: 日期、时间和日历模块
    Python(18):Python模块基础
    微信官方文档
    Python(17):Python面向对象高级
    Python(16):Python面向对象进阶
    Python(15):Python面向对象基础
    Python(14):python异常处理
  • 原文地址:https://www.cnblogs.com/aloneindefeat/p/10654102.html
Copyright © 2011-2022 走看看