【问题标题】:To get redirected URL with requests使用请求获取重定向 URL
【发布时间】:2020-06-21 20:12:28
【问题描述】:

我想通过请求获得重定向的 URL。我的网址是 https://twitter.com/i/user/2274951674 。当我在浏览器中输入此网址时,网址重定向https://twitter.com/ozanbayram01

r=requests.get("https://twitter.com/i/user/2274951674")`

r.url #doesnt work

【问题讨论】:

  • 您是否尝试阅读文档?我相信他们提到了 r.history
  • 是的,我做了,但它不起作用,它返回空列表。
  • r.url 应该是请求的网址。要查看响应中的重定向,请使用 r.history
  • 是的,我做了,但它不起作用,它返回空列表
  • 它没有重定向。我怀疑它只是使用 javascript 或其他东西来修改浏览器中的 url。页面加载完成后,也许使用 selenium 并在浏览器中捕获 url。

标签: python url redirect python-requests


【解决方案1】:

我没有任何运气通过使用前面帖子中提到的请求来获得重定向的 url。但我能够使用 webbrowser 库解决此问题,然后使用 sqlite 3 获取浏览器历史记录,并能够获得您正在寻找的结果。

如果您找到其他解决方案,请告诉我。

这是我的代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 2019-03-02
    相关资源
    最近更新 更多