[英]How to get Meta Description tag of a web page using python or javascript
[英]How can I use either PHP or JavaScript to display the contents of the description meta tag in the body text of a web page?
我的網站以 class.page.php 構造函數/析構函數開頭,其中包含元信息、頁面標題和頁腳。
<?php
class page{
private $title;
private $pageDescription;
public function __construct($title, $pageDescription){
$this->title = $title;
$this->pagedescription = $pageDescription;
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title</title>
<meta name="description" content="My Page Description;">
// … etc …
function __destruct()
{
// … etc …
}
}
?>
每個頁面都以這個 PHP 腳本開始,需要 class.page.php 並將該頁面的標題和描述插入到頭部。
<?php
require_once("inc/class.page.php");
// Insert title, page description.
$page = new page('My Page Title','My Page Description');
?>
我的目標是能夠從元標記插入描述內容......
<meta name="description" content="I want this also to show up between the h2 tags.">
...在正文中的h2
標簽之間,即:
<h2>How do I insert the page description here?</h2>
我能夠讓頁面標題顯示在h1
標簽之間,如下所示,但我無法弄清楚如何對元描述內容執行類似的操作。
<h1 id="pagetitle"></h1>
<script>
document.getElementById('pagetitle').innerHTML = document.title;
</script>
我更願意為此找到一個 PHP 解決方案(以及頁面標題,就此而言)。 但我也很樂意使用 JavaScript 來做到這一點。
您可以使用meta[name=description]
選擇器選擇<meta name="description">
元素:
const content = document.querySelector('meta[name=description]').getAttribute('content'); document.getElementById('pagetitle').textContent = content;
<meta name="description" content="I want this also to show up between the h2 tags."> <h1 id="pagetitle"></h1>
還記得在故意插入 HTML 標記時只使用innerHTML
- 如果您只想插入文本,請改用textContent
。 ( innerHTML
不太合適,速度較慢,如果設置的內容innerHTML
則可以允許任意代碼執行)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.