1

我正在尝试将我的嵌入推文 html 转换为图片。模块:

import tweepy as tw
import imgkit

这就是我使用 tweepy 嵌入推文的方式:

def get_embed():
    # ----------------------------------- Twitter API
    consumer_key = "consumer_key"
    consumer_secret = "consumer_secret"
    access_token = "access_token"
    access_token_secret = "access_token_secret"
    # ------------------ Activating Tweepy session
    auth = tw.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    tw_api = tw.API(auth)
    url = "https://twitter.com/DisneyPlusNL/status/1427605982524461082?s=20"
    result = tw_api.get_oembed(url, theme="dark")
    return result['html']

这就是我尝试将其转换为图片的方式:

def cnv2image(html):
    imgkit.from_string(html, 'imagekit.png')

cnv2image(get_embed())

但结果不是它应该的样子。

预期结果: https ://drive.google.com/file/d/1C3Cny8hpbL4MfKH2sxynBhsDM9WsnNts/view?usp=sharing

结果: https ://drive.google.com/file/d/1NZZykQ1fuzvf9zRLkCVl6wTcGPCa5cgE/view?usp=sharing

4

2 回答 2

1

您甚至不需要tweepyimgkit执行此操作,也不需要其他人的 API,只需使用selenium

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import time

url = "https://twitter.com/DisneyPlusNL/status/1427605982524461082?s=20"

# Configure Firefox to work headlessly (no window popping up)
options = Options()
options.headless = True
driver = webdriver.Firefox(options=options)

# To make sure no other visual elements overlap the Tweet.
driver.set_window_position(0, 0)
driver.set_window_size(2000, 2000)

# Fetch the Tweet URL
driver.get(url)

# Just to make sure all elements load first
time.sleep(2)

# Sometimes we need to click onto the tweet first, be we also sometimes don't.
try:
    driver.find_element_by_xpath("/html/body/div/div/div/div[2]/main/div/div/div/div[1]/div/div[2]/div/section/div/div/div[2]/div/div/article/div/div/div/div[2]/div[2]/div[2]/div[1]/div/span").click()
except:
    pass

# Screenshot the Tweet
img = driver.find_element_by_xpath("/html/body/div/div/div/div[2]/main/div/div/div/div[1]/div/div[2]/div/section/div/div/div[1]/div/div/article").screenshot_as_png

# Write the image data to a file
with open("tweet.png", "wb") as file:
    file.write(img)

# Close the headless browser
driver.close()

此代码将创建一个名为的图像文件tweet.png,如下所示:

在此处输入图像描述

您可以selenium通过pip install selenium. 此代码使用 Firefox,但您也可以将其配置为使用 Chrome,您将获得完全相同的输出。网上有很多关于如何完全配置它的资源。

于 2021-08-19T06:53:59.410 回答
1

所以,你只想要推文的截图,对吧?

好吧,如果您不介意,我建议您使用另一个 API 服务:https ://apiflash.com/

它可以从我个人使用的任何网站截取屏幕截图,非常好用,而且它也是免费的

您还可以提及目标 HTML 标记的 CSS 以仅获取其屏幕截图

我希望它对你有用并且对你有用......

编辑:它正在工作,这是输入的获取网址

https://api.apiflash.com/v1/urltoimage?access_key={api-key=goes-here}&delay=10&element=.css-1dbjc4n&format=png&fresh=true&no_ads=true&no_cookie_banners=true&no_tracking=true&quality=100&response_type=image&url=https% 3A%2F%2Ftwitter.com%2FDisneyPlusNL%2Fstatus%2F1427605982524461082%3Fs%3D20

和输出图像... 在此处输入图像描述

是的,它将整个页面作为屏幕截图发布,我只处理选择性 html 标记

于 2021-08-18T14:49:27.667 回答