Via Requests
import requestsfrom urllib.parse import urlencodeurl = 'https://twitter.com/jack/status/20'query_string = urlencode({'url': url}) # 'omit_script': 1oembed_url = f"https://publish.twitter.com/oembed?{query_string}"r = requests.get(oembed_url)if r.status_code == 200: result = r.json() html = result['html'].strip()
Output
{ "url":"https:\/\/twitter.com\/jack\/status\/20", "author_name":"jack", "author_url":"https:\/\/twitter.com\/jack", "html":"\u003Cblockquote class=\"twitter-tweet\"\u003E\u003Cp lang=\"en\" dir=\"ltr\"\u003Ejust setting up my twttr\u003C\/p\u003E— jack (@jack) \u003Ca href=\"https:\/\/twitter.com\/jack\/status\/20?ref_src=twsrc%5Etfw\"\u003EMarch 21, 2006\u003C\/a\u003E\u003C\/blockquote\u003E\n\u003Cscript async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"\u003E\u003C\/script\u003E\n", "width":550, "height":null, "type":"rich", "cache_age":"3153600000", "provider_name":"Twitter", "provider_url":"https:\/\/twitter.com", "version":"1.0"}
Via Tweetpy
pip install tweepy
import tweepy# create twitter developer account at https://developer.twitter.com/auth = tweepy.OAuthHandler(TWITTER_CONSUMER_API_KEY, TWITTER_CONSUMER_API_SECRET)# auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth)tweet_id = '20'result = api.get_oembed(tweet_id) # , omit_script=Truehtml = result['html'].strip()
NOTE: Python Get Twitter ID From Url
References: