杰瑞科技汇

Python requesocks 64位兼容性问题如何解决?

Of course! The term "python requesocks 64" typically refers to using the requests library with SOCKS proxies on a 64-bit version of Python. This is a very common task for developers who need to route their web traffic through proxies for tasks like web scraping, privacy, or accessing geo-restricted content.

Python requesocks 64位兼容性问题如何解决?-图1
(图片来源网络,侵删)

The standard requests library does not natively support SOCKS proxies. To do this, you need to install a special library that provides this capability.

Here's a complete guide covering everything you need to know.


The Key Library: requests[socks]

The most popular and straightforward way to add SOCKS support to requests is by installing the requests library with the optional socks extra. This installs the requests library and the underlying urllib3[socks] library that provides the SOCKS functionality.

Installation

Open your terminal or command prompt and run the following command:

Python requesocks 64位兼容性问题如何解决?-图2
(图片来源网络,侵删)
# This installs requests and the SOCKS adapter
pip install requests[socks]

Note on "64": The 64 in your query almost certainly refers to using a 64-bit version of Python. This is the standard and recommended version for modern operating systems. The installation command above works identically for both 32-bit and 64-bit Python. You can verify your Python architecture by running:

python -c "import struct; print(struct.calcsize('P') * 8)"

If the output is 64, you are running a 64-bit version.


How to Use SOCKS Proxies with requests

Once installed, using a SOCKS proxy is as simple as providing a special URL to the proxies argument in your requests call.

Basic GET Request

Here’s a simple example of making a GET request through a SOCKS proxy.

Python requesocks 64位兼容性问题如何解决?-图3
(图片来源网络,侵删)
import requests
# Define your SOCKS proxy
# Format: 'socks5://user:password@host:port'
# For a public proxy without authentication, it's just 'socks5://host:port'
# Common SOCKS ports are 1080 (SOCKS5) and 1081 (SOCKS4)
proxy_url = 'socks5://user:password@your_proxy_ip:1080' 
proxies = {
    'http': proxy_url,
    'https': proxy_url,
}
try:
    # Make the request using the proxies dictionary
    response = requests.get('http://httpbin.org/ip', proxies=proxies, timeout=10)
    # httpbin.org/ip returns the IP address seen by the server
    # This should be the IP of your proxy, not your own IP
    print(f"Request successful! Status Code: {response.status_code}")
    print("Response JSON:")
    print(response.json())
    print(f"\nIP address used: {response.json()['origin']}")
except requests.exceptions.ProxyError as e:
    print(f"Proxy Error: Could not connect to the proxy. {e}")
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

SOCKS4 vs. SOCKS5

You can specify the SOCKS version in the URL:

  • socks5://: Uses SOCKS5, which is the newer and more common version. It supports authentication and IPv6. (Recommended)
  • socks4://: Uses the older SOCKS4 protocol, which does not support authentication.
# Example using SOCKS4
proxy_url_socks4 = 'socks4://your_proxy_ip:1081'
proxies_socks4 = {'http': proxy_url_socks4, 'https': proxy_url_socks4}
# Example using SOCKS5 (default)
proxy_url_socks5 = 'socks5://your_proxy_ip:1080'
proxies_socks5 = {'http': proxy_url_socks5, 'https': proxy_url_socks5}

Complete Example: Scraping with a SOCKS Proxy

Let's imagine you want to scrape the title of a website from behind a SOCKS proxy.

import requests
from bs4 import BeautifulSoup
# --- Configuration ---
# Replace with your actual SOCKS proxy details
SOCKS_PROXY = 'socks5://192.168.1.10:1080' # Example of a local proxy
TARGET_URL = 'https://www.python.org'
# --- Setup ---
proxies = {
    'http': SOCKS_PROXY,
    'https': SOCKS_PROXY,
}
# It's good practice to set a User-Agent
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
print(f"Attempting to scrape '{TARGET_URL}' using proxy '{SOCKS_PROXY}'...")
try:
    # Make the GET request
    response = requests.get(TARGET_URL, proxies=proxies, headers=headers, timeout=15)
    response.raise_for_status()  # This will raise an HTTPError for bad responses (4xx or 5xx)
    # Parse the HTML content
    soup = BeautifulSoup(response.text, 'html.parser')
    # Find the page title
    if soup.title:
        page_title = soup.title.string.strip()
        print("\n--- Success! ---")
        print(f"Page Title: '{page_title}'")
    else:
        print("\n--- Success! ---")
        print("Could not find a title tag on the page.")
except requests.exceptions.ProxyError:
    print("\n--- Error ---")
    print("Failed to connect to the SOCKS proxy. Please check the proxy address and your network connection.")
except requests.exceptions.SSLError:
    print("\n--- Error ---")
    print("An SSL error occurred. This can sometimes happen with proxies. Try using 'http://' instead of 'https://' in your target URL if the site supports it.")
except requests.exceptions.RequestException as e:
    print(f"\n--- An Unexpected Error Occurred ---")
    print(e)

Troubleshooting Common Issues

Issue Possible Cause & Solution
requests.exceptions.ProxyError Cause: The most common error. It means requests couldn't connect to the proxy server.
Solution:
1. Check Proxy Address: Is the IP address and port correct?
2. Check Proxy Protocol: Are you using socks5:// or socks4:// correctly?
3. Test Proxy: Use a tool like telnet your_proxy_ip 1080 to see if the proxy is reachable from your machine.
4. Check Credentials: If your proxy requires a username/password, ensure they are correct and URL-encoded.
requests.exceptions.SSLError Cause: The proxy might be having trouble handling SSL/TLS connections.
Solution: Try adding verify=False to your requests.get() call, but be aware this makes your connection insecure. response = requests.get(..., verify=False). A better solution is to find out why the proxy is failing the SSL handshake.
ModuleNotFoundError: No module named 'urllib3.contrib.socks' Cause: You installed requests but not the socks extra.
Solution: Run pip install requests[socks] or pip install urllib3[socks].
The IP address in the response is my own IP Cause: The proxy is not being used.
Solution:
1. Double-check the proxies dictionary is correctly passed to the requests call.
2. Ensure you are not using a system-wide proxy that is interfering.
3. Verify the proxy URL is correct.

Alternative: The requesocks Library

You might also see references to a library literally named requesocks. This was an older, forked version of requests that had SOCKS support built-in directly.

You should generally avoid using this library today. It is unmaintained and can cause conflicts with the modern requests library. The requests[socks] method is the current, recommended best practice.

分享:
扫描分享到社交APP
上一篇
下一篇