簡體   English   中英

urllib2請求問題

[英]urllib2 Request issue

我正在嘗試使用urllib2打開頁面

 req = urllib2.Request("http://1033kissfm.com",
        headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko/20100101 Firefox/11.0'})
 response = urllib2.urlopen(req)
 rstPage = response.read()

響應是

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.0.3</center>
</body>
</html>

但是當我在瀏覽器中打開此URL時,它的工作正常

http://1033kissfm.com

在瀏覽器中,它重定向到

http://www.1033kissfm.com/pages/main

頁。

我解決了這個問題,因為我認為圖書館不提供任何處理重定向的支持。 此代碼將有助於找到重定向以獲取正確的響應

def get_hops(url):
    redirect_re = re.compile('<meta[^>]*?url=(.*?)["\']', re.IGNORECASE)
    hops = []
    while url:
            if url not in hops:
                hops.insert(0, url)
            response = urllib2.urlopen(url)
            if response.geturl() != url:
                hops.insert(0, response.geturl())
                # check for redirect meta tag
            match = redirect_re.search(response.read())
            if match:
                url = urlparse.urljoin(url, match.groups()[0].strip())
            else:
                url = None
    return hops

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM