如何确保使用列表中的套接字发出BS4请求?

2024-05-14 22:15:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似这样的代理列表,我想用python进行抓取:

proxies_ls = [  '149.56.89.166:3128',
            '194.44.176.116:8080',
            '14.203.99.67:8080',
            '185.87.65.204:63909',
            '103.206.161.234:63909',
            '110.78.177.100:65103']

并使用bs4和请求模块crawlSite(url)创建了一个函数来废弃url。代码如下:

^{pr2}$

我要做的是确保在连接中只使用该列表中的代理。 随机部分

 randProxy=random.choice(proxies_ls)

工作正常,但是检查代理是否有效的部分,主要是因为我仍然得到200作为一个“虚构的代理”的响应。在

如果我将列表缩减为:

proxies_ls = ['149.56.89.166:3128']

如果代理不起作用,我仍然得到200作为回应!(我尝试过使用类似https://pt.infobyip.com/proxychecker.php的代理检查器,但它不起作用…)

所以我的问题是(我会列举一下,这样更容易): a) 为什么我得到的回复是200而不是4xx? b) 如何强制请求使用我想要的代理?在

谢谢你

尤尼托。在


Tags: 模块函数代码url代理列表randomls
2条回答

所以,基本上,如果我答对了你的问题,你只需要检查一下代理是否有效。requests有一个异常处理程序,您可以这样做:

from requests.exceptions import ProxyError
try:
    response = requests.get(url,proxies = {'https':randProxy},headers=header,timeout=30)
except ProxyError:
    # message proxy is invalid

仔细阅读文档,您必须在字典中指定以下内容:

http://docs.python-requests.org/en/master/user/advanced/#proxies

  • 使用代理的协议是什么
  • 代理使用什么协议
  • 代理的地址和端口

“工作”dict应如下所示:

proxies = {
    'https': 'socks5://localhost:9050'
}

这将只代理所有https请求。这意味着它不会代理http。在

因此,要代理所有的网络流量,您应该如下配置dict:

^{pr2}$

当然,如果有必要,也可以用IP地址代替。其他情况请参见以下示例:

$ python
>>> import requests
>>> proxies = {'https':'http://149.58.89.166:3128'}
>>> # Get a HTTP page (this goes around the proxy)
>>> response = requests.get("http://www.example.com/",proxies=proxies)
>>> response.status_code
200
>>> # Get a HTTPS page (so it goes through the proxy)
>>> response = requests.get("https://www.example.com/", proxies=proxies)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 70, in get
    return request('get', url, params=params, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 56, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 488, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 609, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 485, in send
    raise ProxyError(e, request=request)
requests.exceptions.ProxyError: HTTPSConnectionPool(host='www.example.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f7d1f448c10>: Failed to establish a new connection: [Errno 110] Connection timed out',)))

相关问题 更多 >

    热门问题