shell 从URL列表中获取页面标题

wfsdck30  于 2023-08-07  发布在  Shell
关注(0)|答案(2)|浏览(101)

我有一个URL列表,我需要在另一个列表中保存页面标题。wget或curl似乎是正确的方法,但我不知 prop 体如何操作。你能帮忙吗?谢啦,谢啦

wlzqhblo

wlzqhblo1#

你是说类似的事吗

wget_title_from_filelist.sh

#!/bin/bash
while read -r URL; do
    echo -n "$URL --> "
    wget -q -O - "$URL" | \
       tr "\n" " " | \
       sed 's|.*<title>\([^<]*\).*</head>.*|\1|;s|^\s*||;s|\s*$||'
    echo
done

字符串

filelist.txt

https://stackoverflow.com
https://cnn.com
https://reddit.com
https://archive.org

用法

./wget_title_from_filelist.sh < filelist.txt

输出

https://stackoverflow.com --> Stack Overflow - Where Developers Learn, Share, &amp; Build Careers
https://cnn.com --> CNN International - Breaking News, US News, World News and Video
https://reddit.com --> reddit: the front page of the internet
https://archive.org --> Internet Archive: Digital Library of Free &amp; Borrowable Books, Movies, Music &amp; Wayback Machine

解释

tr "\n" " "     # remove \n, create one line of input for sed

sed 's|.*<title>\([^<]*\).*</head>.*|\1|;   # find <title> in <head>
s|^\s*||;                                   # remove leading spaces
s|\s*$||'                                   # remove trailing spaces

6xfqseft

6xfqseft2#

改进@utlox的答案,以处理具有属性(<title k=v>)的标题标签:

#!/bin/bash
while read -r URL; do
    echo -n "$URL --> "
    wget -q -O - "$URL" | \
       tr "\n" " " | \
       sed 's|.*<title[^>]*>\([^<]*\).*</head>.*|\1|;s|^\s*||;s|\s*$||'
    echo
done

字符串

相关问题