使用请求库(Python3)从洋葱链接获取HTML内容

2024-03-29 14:40:05 发布

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

我尝试使用请求库(或urllib.请求). 我试过各种各样的方法,但似乎都不管用。在

一开始,我只是尝试使用请求库连接到一个代理,然后获取facebook deep web的HTML代码:

import requests

session = requests.session()
session.proxie = {}
session.proxies['http'] = 'socks5h://localhost:9050'
session.proxies['https'] = 'socks5h://localhost:9050'

r = requests.get('https://facebookcorewwwi.onion/')

print(r.text)

但是,当我这样做时,到代理的连接不起作用(无论有没有代理,我的IP都保持不变)。在

我得到以下错误:

^{pr2}$

在做了一些研究之后,我看到有人试图做类似的事情,解决方案是在导入requests/urllib.request库之前连接到代理。在

所以我尝试使用库sockssocket进行连接:

import socks
import socket

def create_connection(address, timeout=None, source_address=None):
    sock = socks.socksocket()
    sock.connect(address)
    return sock

socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)

# patch the socket module
socket.socket = socks.socksocket
socket.create_connection = create_connection



import urllib.request

with urllib.request.urlopen('https://facebookcorewwwi.onion/') as response:
    html = response.read()
    print(html)

当我这样做时,我的代理连接被拒绝:

urllib.error.URLError: <urlopen error Error connecting to SOCKS5 proxy 127.0.0.1:9050: [Errno 61] Connection refused>

我尝试使用requests库,而不是像follow一样(只需从import urllib.request的行中替换它)

import requests
r = requests.get('https://facebookcorewwwi.onion/')
print(r.text)

但是这里我得到了一个错误:

raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='facebookcorewwwi.onion', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x10d93ee80>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))

似乎无论我做什么,我的代理连接都会被拒绝。有没有人有其他的解决方案或方法来解决这个问题?在


Tags: httpsimport代理addressrequestsessioncreatesocket