来自file_get_contents的变量响应'https://en.wikipedia.org/wiki/Category:Upcoming_singles'

问题描述 投票:4回答:4
file_get_contents('https://en.wikipedia.org/wiki/Category:Upcoming_singles');  

使用Chrome网络浏览器(显示4个产品)返回访问同一地址的不同回复(2个产品)。

经过检查,我怀疑这可能与此有关

使用...时间戳保存在解析器缓存键中...

在html中返回。当我使用file_get_contents()时,时间戳更旧

有关如何使用file_get_contents()获取最新信息的任何想法?

谢谢!

php caching screen-scraping wikipedia
4个回答
5
投票

假设file_get_contents正在发出http请求,最好检查指定的用户代理。

我听说过使用某些用户代理获取数据时出现问题。看看this question

您可以使用流上下文指定其他选项(包括用户代理):

<?php
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);

看一下file_get_contents docs

另外,正如杰克所说,cURL是一个更好的选择。

编辑:

你弄错了。您要添加的是不同的用户代理。例如,使用mozilla firefox中的用户代理可以获得4个结果:

<?php

    $opts = array(
      'http'=>array(
        'method'=>"GET",
        'header'=>"Accept-language: en\r\n" .
                  "User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; es-AR; rv:1.9.2.23) Gecko/20110921 Ubuntu/10.10 (maverick) Firefox/3.6.23"
      )
    );

    $context = stream_context_create($opts);

    // Open the file using the HTTP headers set above
    $file = file_get_contents('http://en.wikipedia.org/wiki/Category:Upcoming_singles', false, $context);
    print $file;

但是,我认为这不是“合法的”,欺骗它并不好。我认为必须有维基百科提供的任何其他用户代理从外部应用程序获取其数据。


2
投票

在任何情况下,你真的应该使用MediaWiki API而不是试图从人类可读的类别页面屏幕抓取信息。例如,使用try this querylist=categorymembers

一些说明:

  • 选择合适的results format(对于PHP,可能是format=php)。
  • 每个查询的默认限制为10个结果,但您可以使用cmlimit=max将其增加到500。之后,你需要使用query continuation mechanism

您也可以使用现有的MediaWiki API client libraries之一来处理这些和其他小细节。

最后,请与维基媒体服务器保持良好关系:不要同时发送多个查询,并在本地缓存结果,如果您将很快再次需要它们。在User-Agent标题中包含您的联系信息(URL或电子邮件地址)是个好主意,这样,如果您的代码导致过多的服务器负载,维基媒体的系统管理员可以轻松地与您联系。


2
投票

根据Wikimedia User-Agent policy,要求所有请求都标识自己。我强烈建议不要伪造浏览器用户代理。没有必要这样做。

数以百万计的机器一直访问维基百科和其他维基媒体基金会项目。只是确定自己,你的脚本,这并不难!

// Identify your bot, script, or company.
// E.g. Link to a website, or provide an e-mail address.
ini_set( 'user_agent', 'MyBot/1.0; John Doe (contact: [email protected])' );

// Open the file using the HTTP headers set above
$contents = file_get_contents( 'http://en.wikipedia.org/wiki/Sandbox' );
echo $contents;

1
投票

尝试使用cURL并设置标题以获取最新信息,而不是缓存(抱歉,我不记得要设置的确切标题)

© www.soinside.com 2019 - 2024. All rights reserved.