TLDR ; 真正的,最好的答案可能是从 API 获取 Twitter 卡的副本
答案建议检查对 URL 的请求并检查 HTML 元素。这适用于您的示例推文,但不幸的是,它可能不够通用,无法适用于所有其他推文。
例如,我使用了示例中可能没有的硬编码标签。但可以肯定的是,这可以作为一个起点,并适用于所有推文。
最重要的是证明它可以做到。
import tweepy
from tweepy import OAuthHandler
import requests
# fill values
consumer_key = ''
consumer_secret = ''
access_token = ''
access_secret = ''
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
tweet_id = 1021517076069056514
status = api.get_status(id=tweet_id)
tweet_url = status.entities['urls'][0]['expanded_url']
r = requests.get(tweet_url)
from bs4 import BeautifulSoup
soup = BeautifulSoup(r.content, 'html.parser')
media_container = soup.select('div.card2.js-media-container')
tweet_card = media_container[0].select('div.js-macaw-cards-iframe-container')
tweet_card_url = tweet_card[0]['data-full-card-iframe-url']
twitter_base_url = 'http://www.twitter.com'
r2 = requests.get(''.join([twitter_base_url, tweet_card_url]))
final_page = r2.content
soup2 = BeautifulSoup(final_page, 'html.parser')
final_data = soup2.find('img', {'class': 'u-block'})
headline = final_data['alt']
image_link = final_data['data-src']
print 'Headline: {}'.format(headline)
print 'Image Link: {}'.format(image_link)
得到:
Headline: Global central banks have rattled bond markets
Image Link: https://pbs.twimg.com/card_img/1021513789722841093/LQWGa8uL?format=jpg&name=600x314