繁体   English   中英

如何从 snscrape 获取 substring(图片 url)?

[英]How to get the substring (photo url) from the snscrape?

编辑,因为我意识到它也有 vedio 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 从 twitter 抓取推文时,我想从照片中过滤照片图像。 我得到如下媒体 object:

media=[Photo(previewUrl='https://pbs.twimg.com/media/FePrYL7WQAQDKEB?format=jpg, fullUrl='https://pbs.twimg.com/media/FePrYL7WQAQDKEB?format=jpg&name=large')]

那么我怎样才能得到 PreviewUrl'https://pbs.twimg.com/media/FePrYL7WQAQDKEB?format=jpg, 和完整的 url sperately',

使用 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])

然后您将获得每个推文行的网址 [如果有的话]。

如果你想把它全部放在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 ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM