Edit,因为我意识到它也有视频url,我的问题是,如何才能在下面的循环中只获取照片url?我想添加一个名为photourl的属性,它是来自媒体的完整url。
import snscrape.modules.twitter as sntwitter
import pandas as pd
# Creating list to append tweet data to
attributes_container = []
# Using TwitterSearchScraper to scrape data and append tweets to list
for i,tweet in enumerate(sntwitter.TwitterSearchScraper('sex for grades since:2021-07-05 until:2022-07-06').get_items()):
if i>150:
break
attributes_container.append([tweet.user.username, tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content, tweet.media])
# Creating a dataframe to load the list
tweets_df = pd.DataFrame(attributes_container, columns=["User", "Date Created", "Number of Likes", "Source of Tweet", "Tweet","media"])
当我使用snscrape从推特上刮推特时,我想从照片图中过滤照片图像。我得到的媒体对象如下:
media=[Photo(previewUrl='https://pbs.twimg.com/media/FePrYL7WQAQDKEB?format=jpg, fullUrl='https://pbs.twimg.com/media/FePrYL7WQAQDKEB?format=jpg&name=large')]
那么我如何才能获取预览URLhttps://pbs.twimg.com/media/FePrYL7WQAQDKEB?format=jpg,和完整的url",
使用python代码?
感谢
您可以将for
循环更改为:
for i,tweet in enumerate(sntwitter.TwitterSearchScraper('sex for grades since:2021-07-05 until:2022-07-06').get_items()):
if i>150:
break
try:
tweetMedia = tweet.media[0].fullUrl # .previewUrl if you want previewUrl
except:
tweetMedia = tweet.media # or None or '' or any default value
attributes_container.append([tweet.user.username, tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content, tweetMedia])
然后你会得到每个tweet行的url(如果有的话(。
如果你想把它全部放在append
语句中,你可以把它改成:
attributes_container.append([
tweet.user.username, tweet.date, tweet.likeCount,
tweet.sourceLabel, tweet.content,
(tweet.media[0].fullUrl if tweet.media
and hasattr(tweet.media[0], 'fullUrl')
else tweet.media)
])
[而不是添加try...except
]