【问题标题】:Trying to get source code of a webpage in perl试图在 perl 中获取网页的源代码
【发布时间】:2012-01-05 08:43:35
【问题描述】:

我正在尝试使用 Perl 的“get”函数获取网页的 html 源代码。我已经在 5 个月前编写了代码,并且运行良好,但昨天我做了一个小编辑,但在那之后无论我尝试了多少,它都无法正常工作。 这是我试过的代码。

#!usr/bin/perl
use strict;
use warnings;
use LWP::Simple;
my $link = 'www.google.com';
my $sou = get($link) or die "cannot retrieve code\n";
print $sou;

代码运行良好,但无法检索源代码,而是显示

cannot retrieve code

【问题讨论】:

  • 好的,谢谢,但实际上我正在尝试获取本地服务器页面的来源。当我在我的页面或gold.conf.com/isos/preFCS5.4/LATESTGOOD 中键入“gold/isos/preFCS5.4/LATESTGOOD/”时,我得到了该页面,但它不适用于 perl“get”。请帮助我得到这个.

标签: perl


【解决方案1】:
my $link = 'http://www.google.com';

【讨论】:

  • 好的,谢谢,但实际上我正在尝试获取本地服务器页面的来源。当我在我的页面或gold.conf.com/isos/preFCS5.4/LATESTGOOD 中键入“gold/isos/preFCS5.4/LATESTGOOD/”时,我得到了该页面,但它不适用于 perl“get”。请帮助我得到这个.
  • 我的意思是当我输入 gold/isos/preFCS5.4/LATESTGOOD/ 或 gold.conf.com/isos/preFCS5.4/LATESTGOOD/ 时,我可以在浏览器中看到内容
  • 您的浏览器会在您输入到地址栏中的字符串前静默地添加“http://”。 LWP::Simple 不这样做,所以你需要明确地这样做。
【解决方案2】:

这可能有点晚了,

我一直在努力解决同样的问题,我想我已经知道为什么会发生这种情况。我通常使用 python 抓取网站,我发现在获取请求中包含一些额外的标头信息是理想的。这使网站误以为机器人是一个人,并让机器人访问网站而不是调用 400 错误请求状态代码。

所以我将这种想法应用到我的 Perl 脚本中,这与你的相似,只是添加了一些额外的标题信息。结果给了我网站的源代码,毫不费力。

代码如下:

#!/usr/bin/perl

# This line specifies the LWP version and if not put in place the code will fail.
use LWP 5.64;
 
# This line defines the virtual browser.
$browser = LWP::UserAgent->new;


# This line defines the header infomation that will be given to the website (eg. google) incase the website invokes a 400 bad request status code.
@ns_headers = (
 'User-Agent' => 'Mozilla/4.76 [en] (Win98; U)',
 'Accept' => 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*',
 'Accept-Charset' => 'iso-8859-1,*,utf-8',
 'Accept-Language' => 'en-US',
 );

# This line defines the url that the user agent will browse. 
$url = 'https://www.google.com/';
 
# This line is used to request data from the specified url above.
$response = $browser->get($url, @ns_headers)  or die "cannot retrieve code\n";;



# Decodes responce so the HTML source code is visable.
$HTML = $response->decoded_content;

print($HTML);

我有 LWP::Useragent,因为它可以让您添加额外的标头信息。

我希望这会有所帮助,

我。

PS。抱歉,如果您已经知道了这个问题的答案,只是想提供帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多