您可以为此使用xmlstarlet:
xmlstarlet sel --net --html -t -m "//img" -v "@src" -n 'http://en.wikipedia.org/wiki/Current_members_of_the_United_States_House_of_Representatives'
将为您提供http://en.wikipedia.org/wiki/Current_members_of_the_United_States_House_of_Representatives页面中img标签的所有src字段。
您会注意到输出行缺少标题 http:,因此我们必须添加它。
然后:
while IFS= read -r line; do
[[ $line = //* ]] && line="http:$line"
wget "$line"
done < <(
xmlstarlet sel --net --html -t -m "//img" -v "@src" -n 'http://en.wikipedia.org/wiki/Current_members_of_the_United_States_House_of_Representatives'
)
应该检索图像文件。
从您的评论中,我现在了解您的要求:您想要获取包含 img 节点的 a 节点的所有 href 字段。满足此要求的xpath 是:
//a[img]
因此,
xmlstarlet sel --net --html -t -m "//a[img]" -v "@href" -n 'http://en.wikipedia.org/wiki/Current_members_of_the_United_States_House_of_Representatives'
会给你这些hrefs。
现在,检索到的 URL 不是直接要下载的图像;相反,它是另一个 HTML 页面,其中包含指向所需图像的链接。我使用以下 xpath 选择了这些页面中的图像:
//div[@class='fullImageLink']/a
即,div 节点内的a 节点与class="fullImageLink"。这似乎没问题,启发式的。
那么,应该这样做:
#!/bin/bash
base="http://en.wikipedia.org"
get_image() {
local url=$base$1
printf "*** %s: " "$url"
IFS= read -r imglink < <(xmlstarlet sel --net --html -t -m "//div[@class='fullImageLink']/a" -v "@href" -n "$url")
if [[ -z $imglink ]]; then
echo " ERROR ***"
return 1
fi
imglink="http:$imglink"
echo " Downloading"
wget -q "$imglink" &
}
while IFS= read -r url; do
[[ $url = /wiki/File:* ]] || continue
get_image "$url"
done < <(
xmlstarlet sel --net --html -t -m "//a[img]" -v "@href" -n "$base/wiki/Current_members_of_the_United_States_House_of_Representatives"
)
你会得到比你想要的多一点,但这是一个很好的基础:)。