为什么BeautifulSoup无法检索og:image元数据,而Facebook共享调试器却可以?

问题描述 投票:0回答:1

这是我的 BeautifulSoup 代码:

from bs4 import BeautifulSoup
import requests
 
html = requests.get("https://vt.tiktok.com/ZSLvos3x2/").text
soup = BeautifulSoup(html, 'html.parser')

image = soup.find("meta",  {"property":"og:image"})
print(image)

结果内容为空:

<meta content="" data-rh="true" property="og:image"/>

但是,Facebook 的共享调试器可以读取它

<meta property="og:image" content="https://p16-sign-va.tiktokcdn.com/tos-maliva-p-0068/e025f28037a84ad4b86d9437ba70ad2d_1683178221~tplv-photomode-video-share-card:1200:630:20.jpeg?x-expires=1695362400&amp;x-signature=MNuRNoO2lAxX61zDfuqG5mKnI74%3D">

为什么会出现这种差异?

image beautifulsoup facebook-opengraph facebook-debugger
1个回答
0
投票

结果内容为空,这意味着该内容来自 JavaScript,您必须使用 Selenium 或类似的浏览器自动化 Python 库。 获取 js 内容后,您可以使用 BeautifulSoup 解析 HTML,然后使用正则表达式获取 og 图像 url

使用正则表达式

og_image = re.find("og:image[^>]+content="([^"]+),soup)
print(og_image.group(1))

完整代码:

import re
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get("https://vt.tiktok.com/ZSLvos3x2/")
time.sleep(3) #here waiting three seconds 
html = driver.page_source
soup = BeautifulSoup(html)
og_image = re.find("og:image[^>]+content="([^"]+),soup)
print(og_image.group(1))
© www.soinside.com 2019 - 2024. All rights reserved.