如何使用 JQuery/JS 获取给定 url(外部 url)的网页标题

IT技术 javascript jquery get title
2021-01-15 09:26:30

我是新手,如果这是一个愚蠢的问题,请原谅我..

所以我想要的是使用 JQuery/JS 获取 URL 的标题。我不想加载 url 的内容,然后解析其中的标签。

让我更清楚一点,我有一组网址,比如 20 个,我想显示标题..我所指的网址不是当前的网址,所以我不能使用 js document.title ..

所以我想做一些类似 SOMEFUNC.title(URL) 的事情并得到它的标题。有没有这样的功能?

3个回答

这样的事情应该工作:

$.ajax({
  url: externalUrl,
  async: true,
  success: function(data) {
    var matches = data.match(/<title>(.*?)<\/title>/);
    alert(matches[0]);
  }   
});

TheSuperTramp 是正确的,如果 externalUrl 在您的域之外,则上述内容将不起作用。而是创建这个 php 文件 get_external_content.php:

<?php
function file_get_contents_curl($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$url = $_REQUEST["url"];
$html = file_get_contents_curl($url);

preg_match('/<title>(.+)<\/title>/',$html,$matches);
$title = $matches[1];

echo  json_encode(array("url" => $url, "title" => $title));

然后在javascript中:

function getTitle(externalUrl){
  var proxyurl = "http://localhost/get_external_content.php?url=" + externalUrl;
  $.ajax({
    url: proxyurl,
    async: true,
    success: function(response) {
      alert(response);
    },   
    error: function(e) {
      alert("error! " + e);
    }
  });
}
啊,@user1014390,你说得对。调用本地文件,在GET(或POST,无所谓)中解析url。一个简单的 php 脚本就可以了。我认为已经有很多这样的 php 示例了:)
2021-03-17 09:26:30
这不适用于外部网址..正如@OptimusCrime 所说,我将尝试使用 php 并解析它
2021-03-20 09:26:30
这可能不起作用,浏览器可能不允许通过 XMLHttpRequest 调用外部 url。w3.org/TR/XMLHttpRequest
2021-03-31 09:26:30
这可以工作。另一种方法是编写一个执行此正则表达式的 php 脚本。
2021-04-08 09:26:30
是的 .. 但我主要关心的是此类请求的数量.. 所以我有大约 20 个网址.. 所以在服务器端这样做需要很长时间!!
2021-04-14 09:26:30

您还可以使用此 API 获取任何网页的标题

http://textance.herokuapp.com/title/

$.ajax({
      url: "http://textance.herokuapp.com/title/www.bbc.co.uk",
      complete: function(data) {
        alert(data.responseText);
      }
});
这是一个我们可以自己运行的插件吗?
2021-03-24 09:26:30
当我尝试使用它时,我得到 XMLHttpRequest 无法加载textance.herokuapp.com/title/http://fortawesome.github.io/...请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问源 ' localhost:3000 '。
2021-03-31 09:26:30
不再有效。对于用户的问题,这也是一个非常依赖外部的解决方案。
2021-04-02 09:26:30
API 已关闭。
2021-04-09 09:26:30
抱歉打错了!您也可以将其与长 URL 一起使用。剪掉 https:// 并将“/”替换为“%2F”。这有效!
2021-04-13 09:26:30

跨域请求不适用于 ajax,但您可以做的是在您的服务器上编写一个脚本来获取给定站点的标题。

如果您使用 PHP,您可以使用 file_get_contents 和 preg_match 函数来获取标题。这里的这个人已经提供了它的代码。

http://www.cafewebmaster.com/php-get-page-title-function

然后在 jQuery 中,您可以将其添加到事件中或将其放入函数中。

//For the purpose of this example let's use google
var url = "http://www.google.com";

$.ajax({
  type: "POST",
  url: "./getURLTitle.php",
  data: "{url: \"" + url + "\"}",
  success: function(data) {
     //do stuff here with the result
     alert(data);
  }   
});