从 urllib2 获取传出端口号

发布于 2024-12-26 13:24:15 字数 483 浏览 3 评论 0原文

我正在使用 Python 2.6.x 和 urllib2 进行一些网页抓取,但我需要每个 HTTP 请求的低级套接字信息(实际上只是本地套接字的端口号)。有谁知道如何得到它?

谢谢

编辑:

好的,我仍在努力解决这个问题,所以我做了我认为应该有效的事情,但当我尝试使用新东西时我没有得到输出。我在这里做错了什么?

from urllib2 import *

class AbstractHTTPHandler(AbstractHTTPHandler):

    def do_open(self, http_class, req):
        """
          ...copy docstring...
        """
        print "woot!"
        ...copy code from urllib2.AbstractHTTPHandler.do_open...

I am using Python 2.6.x and urllib2 to do some web scraping, but I need really low-level socket information (really just the port number of the local socket) for each HTTP request. Does anyone know how to get that?

Thanks

EDIT:

Okay, I'm still trying to get this right, so I did what I thought should work but I'm not getting the output when I try and use the new stuff. What am I doing wrong here?

from urllib2 import *

class AbstractHTTPHandler(AbstractHTTPHandler):

    def do_open(self, http_class, req):
        """
          ...copy docstring...
        """
        print "woot!"
        ...copy code from urllib2.AbstractHTTPHandler.do_open...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

噩梦成真你也成魔 2025-01-02 13:24:15

urllib2 可以在不同的 URL 方案上操作,这些方案甚至可能没有套接字的概念。相反,使用 http.client 的未记录的 sock 属性:

try:
    from http.client import HTTPConnection
except ImportError: # Python<3
    from httplib import HTTPConnection

h = HTTPConnection('example.net', 80)
h.request('GET', '/')
print('Local port: ' + str(h.sock.getsockname()[1]))

urllib2 can operate on different URL schemes, which may not even have a notion of socket. Instead, use http.client's undocumented sock property:

try:
    from http.client import HTTPConnection
except ImportError: # Python<3
    from httplib import HTTPConnection

h = HTTPConnection('example.net', 80)
h.request('GET', '/')
print('Local port: ' + str(h.sock.getsockname()[1]))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文