html元素的解析内容时,Grep无法识别选项“->”

问题描述

我正在尝试使用“ error-icon”类解析div元素的内容,并且grep多次尝试显示无法识别的选项。这是我的代码。请帮助

#!/bin/sh

verifyCard=$1

if [ -z "${verifyCard}" ]; then echo "No argument supplied"; exit 1; fi

response=$(curl 'https://www.isic.org/verify/' -H 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Content-Type: application/x-www-form-urlencoded' -H 'Origin: https://www.isic.org' -H 'Connection: keep-alive' -H 'Referer: https://www.isic.org/verify/' -H 'Cookie: PHPSESSID=46plnh6b31e2pusv1do6thfbm7; AWSELB=AF73034F18B38D7DCED6DEDC728D31BA3F3A73F96747FEE7FA7C4F7A74BC9954E5928CBDDD5C053FFB2A37CE37136C4BA008B15163192B34CFA04D35BEC4ED0D0D2913A2FB; AWSELBCORS=AF73034F18B38D7DCED6DEDC728D31BA3F3A73F96747FEE7FA7C4F7A74BC9954E5928CBDDD5C053FFB2A37CE37136C4BA008B15163192B34CFA04D35BEC4ED0D0D2913A2FB; _ga=GA1.2.650910486.1600495658; _gid=GA1.2.731428038.1600495658; _gat=1' -H 'Upgrade-Insecure-Requests: 1' --data-raw 'verify_card_number=${$verifyCard}')

output=$(grep -o '<div class="error-icon">[^<]*' "$response" | grep -o '[^>]*$')

echo "$output"

解决方法

response=$(curl ...)

curl命令的输出放入名为response的变量中。

在您的grep命令中,您尝试将变量的扩展作为参数传递。

output=$(grep -o '<div class="error-icon">[^<]*' "$response" | ...)

grep尝试将值解释为命令行参数,根据实际输出,可能会导致各种错误。在我的测试中,我收到一条消息grep: <some html code>: File name too long,因为它试图将其解释为文件名参数。

您应该将数据保存在文件中,并将其传递给grep。根据需要调整临时文件的名称和位置。示例:

#!/bin/sh

verifyCard=$1

if [ -z "${verifyCard}" ]; then echo "No argument supplied"; exit 1; fi

curl -o response-file 'https://www.isic.org/verify/' -H 'User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:80.0) Gecko/20100101 Firefox/80.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Content-Type: application/x-www-form-urlencoded' -H 'Origin: https://www.isic.org' -H 'Connection: keep-alive' -H 'Referer: https://www.isic.org/verify/' -H 'Cookie: PHPSESSID=46plnh6b31e2pusv1do6thfbm7; AWSELB=AF73034F18B38D7DCED6DEDC728D31BA3F3A73F96747FEE7FA7C4F7A74BC9954E5928CBDDD5C053FFB2A37CE37136C4BA008B15163192B34CFA04D35BEC4ED0D0D2913A2FB; AWSELBCORS=AF73034F18B38D7DCED6DEDC728D31BA3F3A73F96747FEE7FA7C4F7A74BC9954E5928CBDDD5C053FFB2A37CE37136C4BA008B15163192B34CFA04D35BEC4ED0D0D2913A2FB; _ga=GA1.2.650910486.1600495658; _gid=GA1.2.731428038.1600495658; _gat=1' -H 'Upgrade-Insecure-Requests: 1' --data-raw 'verify_card_number=${$verifyCard}'

output=$(grep -o '<div class="error-icon">[^<]*' response-file | grep -o '[^>]*$')

rm response-file

echo "$output"

如果您使用bashzsh而不是sh,则有多种方法可以将某些变量值替换为输入文件,例如using a Bash variable in place of a file as input for an executable中的答案。