2016-02-12 136 views
2

我現在學習Python,我想創建一個簡單的工具來打開幾個網站。我有下面的代碼:Python urllib3太多重定向

#!/usr/bin/python 
import urllib3, ssl, certifi 
from urllib3 import Retry, Timeout 

def openurl(url, method = "get"): 
    retries = Retry(connect=500, read=2, redirect=500) 
    http = urllib3.PoolManager(
     cert_reqs = 'CERT_REQUIRED', 
     ca_certs = certifi.where(), 
     retries = retries 
    ) 
    con = urllib3.connection_from_url(url) 
    r = con.request(method, '/trades'); 

openurl("http://www.steamgifts.com") 

但在這個網站腳本返回Caused by ResponseError('too many redirects',)

我嘗試Retry(connect=500, read=2, redirect=500)解決這個問題,但我沒有看到變化。

+0

有沒有可能這裏有一個循環重定向? – DomTomCat

+0

@DomTomCat我的瀏覽器在這個網站上工作。可能存在對腳本的封鎖,我是新手,我不知道如何檢查它 – ventaquil

回答

2

該網站阻止了一些用戶代理。你可以假裝成爲一個真正的網頁瀏覽器,而不是一個鬼鬼祟祟的黑客,通過設置你自己的HTTP請求頭。我對urllib3不熟悉,但使用requests非常簡單。

>>> requests.get('http://www.steamgifts.com/trades') 
<Response [403]> 

>>> requests.get('http://www.steamgifts.com/trades', 
    headers={'User-Agent': 'internet explorer or something'}) 
<Response [200]> 
+0

我嘗試使用:'urllib3.util.request.make_headers(user_agent =「Mozilla/5.0(Windows NT 6.1; WOW64; Trident /7.0; AS; rv:11.0)像Gecko「)'但仍然無法正常工作 – ventaquil

+1

只需使用請求模塊呢?它更加用戶友好。 –

+0

工作,謝謝你:) – ventaquil