首页 > 解决方案 > Shell:如何使用 lynx 将格鲁吉亚(utf-8)字符密钥传递给网站上的特定字段

问题描述

lynx -accept_all_cookies $URL -cmd_script=bar.txt

bar.txt:

key <tab> //get to first field
key <tab> //get to second field
key ძ     //utf=8 input ძ
key ე     //utf=8 input ე
key ბ     //utf=8 input ბ
key ნ     //utf=8 input ნ
key ა     //utf=8 input ა
key <tab> //get to third field
key <tab> //get to fourth field
key <tab> //get to sumbit button
key ^J    //click submit and wait for load
key <tab> //get to hyperlink
key ^J    //click hyperlink and wait for load
key Q     //exit
key y     //confirm exit

上述尝试改编自这个 SO question,适用于 Ascii 字符,但不适用于格鲁吉亚输入字符。

有什么建议么?

标签: shellhttpparsingunicodelynx

解决方案


您要发送的字符是多字节 UTF-8 序列,lynx 命令脚本key命令只发送单个 8 位字节。因此,您必须将字符分成单独的字节并分别发送每个字节。

这有点烦人;最简单的方法可能是-cmd_log在您键入要发送的字符时使用该选项创建日志文件。

但是,您可以使用 bash 执行此操作:

$ georgian=ძებნა
$ (export LC_ALL=C; printf "key 0x%2x\n" $(sed 's/./"& /g' <<<"$georgian"); )
key 0xe1
key 0x83
key 0xab
key 0xe1
key 0x83
key 0x94
key 0xe1
key 0x83
key 0x91
key 0xe1
key 0x83
key 0x9c
key 0xe1
key 0x83
key 0x90

那个 bash 命令可能有点晦涩难懂:-)。这是一个快速细分:

(                         # Start a subshell to isolate environment change
 export LC_ALL=C;         # In the subshell, set the locale to plain ascii
 printf "key 0x%2x\n"     # Apply this format to each argument
        $(                # Substitute the result of running the following
          sed             # Editor command
              's/./"& /g' # Change each byte to <"><byte><space>
              <<<"$georgian"  # Fabricate an input stream for sed
                              # using the value of shell variable $georgian
        );                # End of command substitution
)                         # End of subshell

与 C printf(和其他)不同,shell 会printf重复其模式,直到处理完所有参数。并且,作为另一个特质,如果格式是数字格式(例如%x,它以十六进制格式化其参数并且相应的参数以 a 开头",则用于参数的数字是参数中第二个字符的字符代码(即之后")。

sed命令将字节序列转换为一系列具有这种形式的参数;重要的是不要引用命令替换,这样各个替换将被视为单独的参数。这意味着如果包含任何 shell 元字符,该命令将不起作用,但是由于所有 shell 元字符都是简单的 ascii 字符,因此只要其中的每个字符实际上都是格鲁吉亚语,$georgian就不会有任何问题。$georgian(但不要在字符串中放置空格。它们会被默默地丢弃。)


推荐阅读