Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我可以检索Twitter卡标题和媒体URL吗?_Python_Twitter_Web Scraping_Tweets_Twitter Card - Fatal编程技术网

Python 我可以检索Twitter卡标题和媒体URL吗?

Python 我可以检索Twitter卡标题和媒体URL吗?,python,twitter,web-scraping,tweets,twitter-card,Python,Twitter,Web Scraping,Tweets,Twitter Card,我想从我的tweets中收集所有Twitter卡片标题和url,用于一个项目。例如,对于此tweet:,我希望检索以下信息: 标题:“全球央行喋喋不休扰乱债券市场” 图片链接:“ 现在,我通过查看tweet和卡片来获取这些信息,但我想通过代码和tweet进行迭代。有人知道如何通过编程获得这些信息吗?非常感谢 TLDR;真正的、最好的答案可能是 答案建议检查对URL的请求并检查HTML元素。这适用于您的示例tweet,但不幸的是,它可能不够通用,无法适用于所有其他tweet 例如,我使用了示例

我想从我的tweets中收集所有Twitter卡片标题和url,用于一个项目。例如,对于此tweet:,我希望检索以下信息:

  • 标题:“全球央行喋喋不休扰乱债券市场”
  • 图片链接:“
现在,我通过查看tweet和卡片来获取这些信息,但我想通过代码和tweet进行迭代。有人知道如何通过编程获得这些信息吗?非常感谢

TLDR;真正的、最好的答案可能是

答案建议检查对URL的请求并检查HTML元素。这适用于您的示例tweet,但不幸的是,它可能不够通用,无法适用于所有其他tweet

例如,我使用了示例中发现的硬编码标记,而其他示例中可能没有。 但这当然可以作为一个起点,并适用于所有推文

最重要的是证明了这是可以做到的

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