我正在使用lynx -dump从这个网站中提取Nintendo DS的价格。
例如,假设我要从游戏Yoshi Touch and Go的网页中提取:
/usr/bin/lynx -dump -width=150 http://videogames.pricecharting.com/game/nintendo-ds/Yoshi-Touch-and-Go
一切正常,我可以使用正则表达式轻松拉高价格。问题来自当URL包含撇号(')或与号(&)时,因为这会带来错误。因此,假设我尝试找到游戏Yoshi's Island DS的页面,我将使用以下代码行:
/usr/bin/lynx -dump -width=150 http://videogames.pricecharting.com/game/nintendo-ds/Yoshi's-Island-DS
这会给我这些小错误:
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file
这是我用来调用 -dump 的代码,其中$fullURL
是包含以下内容的字符串:"http://videogames.pricecharting.com/game/nintendo-ds/Yoshi's-Island-DS"。
$command = "/usr/bin/lynx -dump -width=150 $fullURL";
@pageFile = `$command`;
谁能帮我找到一个解决方案,将$fullURL
字符串变成 URL 兼容字符串?
在将 URL 中的'
传递给 shell 之前对其进行转义。Perl 提供了 quotemeta 函数来执行大多数 shell 所需的转义。
my $quoted_URL = quotemeta($fullURL);
$command = "/usr/bin/lynx -dump -width=150 $quoted_URL";
...
还可以使用字符串中的Q
和E
转义来获得相同的结果。
$command = "/usr/bin/lynx -dump -width=150 Q$fullURLE";
...
处理这个问题的正确方法是通过使用 system
/pipe open
的列表形式(替换 qx/backtick 运算符)来避免 shell,参见 Perl 等效的 PHP 的 escapeshellarg。
use autodie qw(:all);
open my $lynx, '-|', qw(/usr/bin/lynx -dump -width=150), $fullURL;
my @pageFile = <$lynx>;
close $lynx;
在极少数情况下,如果这不切实际,则通过 String::ShellQuote 和 Win32::ShellQuote 提供正确的 shell 引用。