【发布时间】:2012-12-10 22:33:42
【问题描述】:
我正在尝试处理用户输入,例如
- 富
- wikt:foo
- 酒吧#hi there
获取输入的https链接,如
- https://en.wikipedia.org/wiki/foo
- https://en.wiktionary.org/wiki/foo
- https://en.wikipedia.org/wiki/Bar#hi_there
我正在尝试以最少手动、最干净的方式来执行此操作,因此我可以将我的脚本上传到某个地方并展示给人们,而不会因为它的低质量而感到羞耻。这意味着:
- 如果我获得的是 http 链接而不是 https,我宁愿不硬编码
s/^http/^https/替换。 - 如果我得到一个不完整的链接,我宁愿不使用正则表达式来添加缺失的东西。
到目前为止,我找到了两个解决方案,但每个都有缺陷。
解析查询
使用 canonicalurl magic word 在 {{canonicalurl:user_input_here}} 上运行解析查询。但是它只提供 http,而不是 https 链接。
#!/usr/bin/perl
use strict;
use warnings;
use MediaWiki::API;
use Data::Dumper;
my $mw = MediaWiki::API->new();
$mw->{config}->{api_url} = 'https://en.wikipedia.org/w/api.php';
my $info_ref = $mw->api ( {
action => 'parse',
prop => 'text',
text => '{{canonicalurl:Hello}}',
} ) or die $mw->{error}->{code} . ': ' . $mw->{error}->{details};
my $html = $info_ref->{parse}{text}{'*'};
print Dumper $html;
信息查询
使用信息查询。但是它不适用于部分,即“Foo#bar”输入将获得链接到“Foo”的输出。
#!/usr/bin/perl
use strict;
use warnings;
use MediaWiki::API;
my $mw = MediaWiki::API->new();
$mw->{config}->{api_url} = 'https://en.wikipedia.org/w/api.php';
sub get_url_by_title(){
my $title = shift;
my $info_ref = $mw->api ( {
action => 'query',
prop => 'info',
inprop => 'url',
iwurl => 1,
titles => $title,
} ) or die $mw->{error}->{code} . ': ' . $mw->{error}->{details};
if (exists $info_ref->{query}{pages}){
return (values $info_ref->{query}{pages})[0]{'fullurl'};
}
elsif (exists $info_ref->{query}{interwiki}){
return (values $info_ref->{query}{interwiki})[0]{'url'};
}
}
【问题讨论】:
标签: perl https mediawiki mediawiki-api