一: 問題描述:
爬蟲微博 信息,出現302跳轉,
比如訪問的URL是:https://weibo.com/2113535642?refer_flag=1001030103_ (圖片中標記為1)
然后跳轉的URL是:https://weibo.com/sgccjsdl?refer_flag=1001030103_&is_hot=1 (圖片中標記為2)
截圖如下所示:
訪問 圖中標記1 的URL的時候,沒有返回任何內容,但是response headers 返回了 圖中標記2 的URL。如下圖所示:
下面是具體實現的代碼過程:
result1 = session.get(url=str(user_url),headers=headers,verify=False,allow_redirects=False) result = result1.content new_requests_url = result1.headers['location'] new_requests_url = "https://weibo.com" + new_requests_url if '<h1 class="username">' not in result: result = session.get(url=str(new_requests_url), headers=headers, verify=False, allow_redirects=False).content
核心代碼是獲得需要跳轉的URL,代碼是 new_requests_url = result1.headers['location']