programing

Python 요청 라이브러리 새 URL 리디렉션

oldcodes 2023. 7. 23. 14:41
반응형

Python 요청 라이브러리 새 URL 리디렉션

Python Requests 문서를 살펴보았지만 달성하려는 기능이 보이지 않습니다.

내 스크립트에서 설정합니다.allow_redirects=True.

페이지가 다른 곳으로 리다이렉트되었는지, 새로운 URL이 무엇인지 알고 싶습니다.

예를 들어 시작 URL이 다음과 같은 경우:www.google.com/redirect

그리고 마지막 URL은.www.google.co.uk/redirected

어떻게 그 URL을 얻을 수 있습니까?

요청 기록을 찾고 있습니다.

response.history속성은 최종 URL로 연결된 응답 목록으로, 다음에서 확인할 수 있습니다.response.url.

response = requests.get(someurl)
if response.history:
    print("Request was redirected")
    for resp in response.history:
        print(resp.status_code, resp.url)
    print("Final destination:")
    print(response.status_code, response.url)
else:
    print("Request was not redirected")

데모:

>>> import requests
>>> response = requests.get('http://httpbin.org/redirect/3')
>>> response.history
(<Response [302]>, <Response [302]>, <Response [302]>)
>>> for resp in response.history:
...     print(resp.status_code, resp.url)
... 
302 http://httpbin.org/redirect/3
302 http://httpbin.org/redirect/2
302 http://httpbin.org/redirect/1
>>> print(response.status_code, response.url)
200 http://httpbin.org/get

이것은 약간 다른 질문에 대한 답이지만, 저는 제 자신이 이것에 갇혀버렸기 때문에, 저는 그것이 다른 사람에게 유용할 수 있기를 바랍니다.

사용할 경우allow_redirects=False그리고 체인을 따라가지 않고 첫 번째 리디렉션 개체로 직접 이동합니다. 그러면 302 응답 개체에서 리디렉션 위치를 직접 이동하고 싶을 뿐입니다.r.url작동하지 않습니다.대신 "위치" 헤더입니다.

r = requests.get('http://github.com/', allow_redirects=False)
r.status_code  # 302
r.url  # http://github.com, not https.
r.headers['Location']  # https://github.com/ -- the redirect destination

대신 url redirect를 처리할 때 통화하는 것이 더 안전할 것 같습니다.GitHub 문제는 여기에서 확인하십시오.

r = requests.head(url, allow_redirects=True)
print(r.url)

문서에는 https://requests.readthedocs.io/en/master/user/quickstart/ #리디렉션-앤-히스토리라는 블러가 있습니다.

import requests

r = requests.get('http://www.github.com')
r.url
#returns https://www.github.com instead of the http page you asked for 

python 3.5의 경우 다음 코드를 사용할 수 있습니다.

import urllib.request
res = urllib.request.urlopen(starturl)
finalurl = res.geturl()
print(finalurl)

짧은 URL(bit.ly , t.co , ...)에서 전체 URL을 얻기 위해 다음 함수를 작성했습니다.

import requests

def expand_short_url(url):
    r = requests.head(url, allow_redirects=False)
    r.raise_for_status()
    if 300 < r.status_code < 400:
        url = r.headers.get('Location', url)

    return url

사용법(짧은 URL은 이 질문의 URL):

short_url = 'https://tinyurl.com/' + '4d4ytpbx'
full_url = expand_short_url(short_url)
print(full_url)

출력:

https://stackoverflow.com/questions/20475552/python-requests-library-redirect-new-url

모든 답변은 최종 URL이 존재하거나 정상적으로 작동하는 경우에 적용됩니다.최종 URL이 작동하지 않을 경우 아래는 모든 리디렉션을 캡처하는 방법입니다.최종 URL이 더 이상 작동하지 않고 URL 기록과 같은 다른 방법으로 오류가 발생하는 시나리오가 있었습니다.
코드 조각

long_url = ''
url = 'http://example.com/bla-bla'
try:
    while True:
        long_url = requests.head(url).headers['location']
        print(long_url)
        url = long_url
except:
    print(long_url)

요청 라이브러리를 사용할 수 없어서 다른 길로 가야 했습니다.이 게시물에 대한 해결책으로 게시하는 코드입니다. (요청이 있는 리디렉션 URL을 보려면)

이렇게 하면 브라우저를 실제로 열고 브라우저가 기록 로그에 URL을 기록할 때까지 기다린 다음 기록의 마지막 URL을 읽습니다.나는 구글 크롬을 위해 이 코드를 작성했지만, 당신이 다른 브라우저를 사용하고 있다면 따라할 수 있을 것입니다.

import webbrowser
import sqlite3
import pandas as pd
import shutil

webbrowser.open("https://twitter.com/i/user/2274951674")
#source file is where the history of your webbroser is saved, I was using chrome, but it should be the same process if you are using different browser
source_file = 'C:\\Users\\{your_user_id}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\History'
# could not directly connect to history file as it was locked and had to make a copy of it in different location
destination_file = 'C:\\Users\\{user}\\Downloads\\History'
time.sleep(30) # there is some delay to update the history file, so 30 sec wait give it enough time to make sure your last url get logged
shutil.copy(source_file,destination_file) # copying the file.
con = sqlite3.connect('C:\\Users\\{user}\\Downloads\\History')#connecting to browser history
cursor = con.execute("SELECT * FROM urls")
names = [description[0] for description in cursor.description]
urls = cursor.fetchall()
con.close()
df_history = pd.DataFrame(urls,columns=names)
last_url = df_history.loc[len(df_history)-1,'url']
print(last_url)

>>https://twitter.com/ozanbayram01

언급URL : https://stackoverflow.com/questions/20475552/python-requests-library-redirect-new-url

반응형