Python http请求(读取代理ip列表)

本文介绍如何使用Python的BeautifulSoup4和urllib2库从网页抓取代理IP列表。通过发送HTTP请求并解析HTML源码,提取出有效的HTTP及HTTPS代理IP地址。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例子:读取代理ip列表

知识点
  • beautifulsoup4
  • urllib & urllib2 & httplib2
  • 网络请求
  • 文件操作
#encoding=utf-8

# from fib import fibonacci
# 这个声明不会把整个fib模块导入到当前的命名空间中,它只会将fib里的fibonacci单个引入到执行这个声明的模块的全局符号表
from bs4 import BeautifulSoup
import urllib2
import urllib


# install beautifulsoup4的步骤
# curl http://www.crummy.com/software/BeautifulSoup/bs4/download/4.1/beautifulsoup4-4.1.2.tar.gz >> beautifulsoup4-4.1.2.tar.gz
# tar zxvf beautifulsoup4-4.1.2.tar.gz
# cd beautifulsoup4-4.1.2
# python setup.py install

# urllib2和urllib的区别(http://blog.youkuaiyun.com/dolphin_h/article/details/45296353)

# urllib2可以接受一个Request类的实例来设置URL请求的headers,urllib仅可以接受URL。这意味着,你不可以伪装你的User Agent字符串等
    # url = 'http://www.someserver.com/cgi-bin/register.cgi'
    # user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'# 将user_agent写入头信息
    # values = {'name' : 'who','password':'123456'}
    # headers = { 'User-Agent' : user_agent }
    # data = urllib.urlencode(values) #{'wd':'D_in'} => wd=D_in
    # req = urllib2.Request(url, data, headers)
    # response = urllib2.urlopen(req)
    # the_page = response.read()


    # url = r'http://www.renren.com/ajaxLogin'
    #
    # #创建一个cj的cookie的容器
    # cj = cookielib.CookieJar()
    # opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    # #将要POST出去的数据进行编码
    # data = urllib.urlencode({"email":email,"password":pass})
    # r = opener.open(url,data)
    # print cj

# urllib提供urlencode方法用来GET查询字符串的产生,而urllib2没有。这是为何urllib常和urllib2一起使用的原因。

# 如果你仅做HTTP相关的,看一下httplib2,比其他几个模块好用
    # def sendhttp():
    #     data = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
    #     headers = {"Content-type": "application/x-www-form-urlencoded",
    #                "Accept": "text/plain"}
    #     conn = httplib.HTTPConnection('bugs.python.org')
    #     conn.request('POST', '/', data, headers)
    #     httpres = conn.getresponse()
    #     print httpres.status
    #     print httpres.reason
    #     print httpres.read()
    #
    # if __name__ == '__main__':
    #     sendhttp()



of = open('proxy2.txt', 'w')

for page in range(1, 2):

    print "start", page
    # 伪装成浏览器进行访问
    headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}
    req = urllib2.Request(url='http://www.xici.net.co/nn', headers=headers)
    resp = urllib2.urlopen(req)

    # req = urllib.urlopen('http://www.xici.net.co/nn')
    # Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
    # User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36
    html_doc = resp.read()
    # 如果源码中中文为乱码,可以使用:print data.decode('u8')

    print 'response code:', resp.getcode()
    print 'response header:', resp.info()
    print 'resp content:', html_doc



    # html_doc = urllib2.urlopen('http://www.xici.net.co/nn/' + str(page)).read()

    # print html_doc
    # 数据内容(摘要):
    #  <table id="ip_list">
    #     <tr>
    #       <th></th>
    #       <th>国家</th>
    #       <th>IP地址</th>
    #       <th>端口</th>
    #       <th>位置</th>
    #       <th>是否匿名</th>
    #       <th>类型</th>
    #       <th>速度</th>
    #       <th>连接时间</th>
    #       <th>验证时间</th>
    #     </tr>
    #     ....
    # </table>
    soup = BeautifulSoup(html_doc)

    trs = soup.find('table', id='ip_list').find_all('tr') #id为ip_list的table,查找其中的tr
    print "trs"

    for tr in trs[1:]:

        # <tr class="">
        #     <td></td>
        #     <td><img alt="Cn" src="http://fs.xicidaili.com/images/flag/cn.png"/></td>
        #     <td>114.105.216.240</td>
        #     <td>6675</td>
        #     <td>
        #             安徽亳州
        #           </td>
        #     <td>高匿</td>
        #     <td>socks4/5</td>
        #     <td>
        #     <div class="bar" title="1.413秒">
        #     <div class="bar_inner fast" style="width:86%">
        #     </div>
        #     </div>
        #     </td>
        #     <td>
        #     <div class="bar" title="0.412秒">
        #     <div class="bar_inner fast" style="width:92%">
        #     </div>
        #     </div>
        #     </td>
        #     <td>13-01-09 15:11</td>
        # </tr>
        print "----------------------------------------\n", tr

        tds = tr.find_all('td')
        ip = tds[2].text.strip()    # 第2个位ip
        port = tds[3].text.strip()
        protocol = tds[6].text.strip()

        print "=============:\n"
        print tds[2].text.strip(), ":", tds[3].text.strip(), " " ,protocol
        print "============="
        if protocol == 'HTTP' or protocol == 'HTTPS':
            of.write('%s=%s:%s\n' % (protocol, ip, port) )
            print '%s=%s:%s' % (protocol, ip, port)

of.close()
### Python 中获取 HTTP 请求客户端 IP 地址的方法 在处理 HTTP 请求时,服务器通常需要知道发起请求的客户端 IP 地址。以下是几种常见的方法来实现这一需求。 #### 使用 Flask 框架 如果使用的是 Flask 框架,则可以利用 `request` 对象中的属性 `remote_addr` 来获取客户端的 IP 地址。需要注意的是,在反向代理环境下(如 Nginx 或 ELB),实际的客户端 IP 可能会被隐藏,此时应读取特定头字段(如 `X-Forwarded-For`)。 ```python from flask import request @app.route('/') def index(): client_ip = request.remote_addr # 获取客户端IP地址 forwarded_for = request.headers.get('X-Forwarded-For') # 如果有反向代理则可能需要这个 return f'Client IP is {client_ip}, X-Forwarded-For is {forwarded_for}' ``` 上述代码展示了如何通过 Flask 的内置对象访问客户端 IP 地址[^1]。 #### 使用 Tornado 框架 对于基于 Tornado 构建的应用程序,可以直接调用 `RequestHandler` 类中的 `request.remote_ip` 属性以提取客户端 IP 地址。 ```python class MainHandler(tornado.web.RequestHandler): def post(self): client_ip = self.request.remote_ip # 提取客户端IP地址 self.write(f'Received from {client_ip}') ``` 这段代码片段说明了 Tornado 如何捕获并返回客户端的 IP 地址。 #### 处理复杂的网络环境 (如负载均衡器) 当应用程序部署于带有负载均衡器或其他中间设备的情况下,原始客户端 IP 将被覆盖为最后一个跳转节点的 IP。为了恢复真实的客户端 IP,需依赖额外的头部信息,比如 `X-Real-IP` 和 `X-Forwarded-For` 字段。这些字段由前置代理设置,并传递给后端服务。 ```python import tornado.web class Handler(tornado.web.RequestHandler): def get_client_ip(self): real_ip = self.request.headers.get("X-Real-Ip") or self.request.remote_ip forward_list = self.request.headers.get("X-Forwarded-For", "").split(",") first_forwarded_ip = forward_list[0].strip() if forward_list else None return first_forwarded_ip or real_ip def post(self): ip_address = self.get_client_ip() self.write({"status": "success", "data": {"ip": ip_address}}) ``` 此外,某些场景下还需要借助 TOA 插件才能正确解析出真正的源 IP 地址,特别是在 TCP/UDP 协议层面的操作系统级别上运行的服务环境中[^3]。 #### 总结 无论采用何种 Web 框架开发应用,都可通过标准库或者框架本身提供的工具轻松取得连接至服务器用户的公网标识符——即其外部可见的 IPv4/v6 数字串形式表现出来的唯一编号集合之一部分;但在存在多级路由转发机制存在的时候,则务必考虑附加参数的存在及其优先级顺序设定问题以便更精准地定位最终使用者的身份特征[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值