wget/curl이 내 URL에 대한 리디렉션을 따르지 않습니다.

wget/curl이 내 URL에 대한 리디렉션을 따르지 않습니다.

당신이에 있다면웹사이트 PDF 다운로드 자동 시작:https://magazines-static.raspberrypi.org/issues/full_pdfs/000/000/308/original/MagPi89.pdf?1576682030

full_pdfs/000/000/308나는 MagPi 잡지에 편지를 쓰고 있었는데 뒤에 오는 숫자 308이 임의의 숫자라고 설명했습니다 .

간단히 말해서: 다운로더의 문제를 해결해야 했습니다.https://github.com/joergi/MagPiDownloader/issues/15모든 이슈를 복사하여 붙여넣을 필요가 없습니다. 그러니 자동 팔로잉이 좋을 것 같아요.

하지만 내가 시도한 모든 것:

curl -JLO https://magpi.raspberrypi.org/issues/89/pdf

그리고

wget --user-agent=Mozilla --content-disposition -E -c https://magpi.raspberrypi.org/issues/80/pdf

백수.

답변1

웹사이트의 HTML을 검사해 보면 "PDF 다운로드" 링크는 http-eqiv="refresh" 속성이 있는 메타 요소를 사용하여 실제 링크로 리디렉션됩니다. 그리고 curl또는 같은 도구는 wget표준을 처리할 수 있습니다 .http 리디렉션, HTML을 구문 분석하거나 해석하지 않으므로 이러한 유형의 리디렉션을 처리할 수 없습니다. 우리는 쉘을 사용하고 있으므로 가능한 해결책 중 하나는 curl페이지를 사용하거나 다운로드 wget하고 html을 필터링하여 http-eqiv="refresh".


사이트에서 더 이상 새 버전에 액세스할 수 없는 것 같기 때문에https://www.raspberrypi.org/magpi-issues/(지난 문제 #86 없음) 현재 스크립트가 작동하는 방식(즉, 본질적으로 PDF 링크의 정적 데이터베이스)이 직관에 반하는 것 같습니다. 이것특별호 다운로드 스크립트나열된 것과 동일한 PDF가 여러 개 있는 것 같습니다.https://magpi.raspberrypi.org/books이지만 스크립트에 최신 버전이 없습니다.

그래서 좀 더 역동적인 스크립트를 만들려고 노력했습니다. 그것은 보인다/서적&/질문사용 가능한/최신 콘텐츠를 확인하세요. 원하는 경우 다음 중 하나를 사용해도 됩니다. zsh, gawk& 를 사용합니다 curl.

#!/usr/bin/env zsh
typeset -aU standard book ignore directory
typeset all latest list_books all_books baseurl="https://magpi.raspberrypi.org/"
setopt extendedglob
function books() {
    typeset -aU books filter minus
    typeset i
    >&2 echo "getting list of available books..."
    books=( $(2>/dev/null curl -fs ${baseurl}books | gawk -v 'RS=href="' -F '"' \
                                                    '$1 ~ /^[/]books[/][^/]*[/]pdf$/{split($1,a,"/"); print "books/"a[3]}') )
    if [[ -z $books ]]
    then
        >&2 echo "unable to find any books"
        return 0
    fi
    case $1 in
        (list)
            printf '\t%s\n' $books
            return 0
            ;;
        (all)
            >&2 echo "Attempting to download all the books, this may take a while ..."
            >&2 printf '\t%s\n' $books
            get_pdfs $books
            return 0
            ;;
        (*)
            for i in $@
            do
                case $i[1] in
                    (-)
                        minus+=( ${(M)books:#*${i:1}*} )
                        books=( ${books:#*${i:1}*} )
                    ;;
                    (*)
                        filter+=( ${(M)books:#*$i*} )
                    ;;
                esac
            done
            if [[ -z $filter && -n $minus ]]
            then
                filter=( ${books:|minus} )
            else
                filter=( ${filter:|minus} )
            fi
            if [[ -z $filter ]]
            then
                >&2 echo "books: no matches found (try book:list)"
                return 0
            else
                >&2 printf '\t%s\n' $filter
                get_pdfs $filter
            fi
        ;;
    esac
}
function issues() {
    typeset -aU issues
    typeset max i
    >&2 printf '%s' "finding most recent issue # ..."
    if ! max=${(M)$(2>/dev/null curl -fs https://magpi.raspberrypi.org/issues | gawk -v 'RS=href="' -F '"' \
                                                                                '$1 ~ /^[/]issues.*[0-9]$/{a=$1;exit}
                                                                                END{if(a){print a} else{exit 1}}')%%[0-9]#}
    then
        >&2 echo "couldn't determine what number the latest issue is."
        return 1
    fi
    >&2 echo "it's $max"
    if [[ $1 = all ]]
    then
        >&2 echo "Attempting to download all the issues, this may take a while ..."
        get_pdfs issues/{1..$max}
        return 0
    fi
    if [[ -n $latest ]]
    then
        issues+="issues/$max"
    fi
    for i in $@
    do
        if [[ $i -le $max ]]
        then
            issues+="issues/$i"
        else
            >&2 echo "issues/$i is larger than $max, ignoring"
        fi
    done
    if [[ -z $issues ]]
    then
        >&2 printf '\t%s\n' "there are no issues to download"
        return 0
    fi
    >&2 printf '\t%s\n' $issues
    get_pdfs $issues
    return 0
}
function get_pdfs() {
    typeset url i
    for i in $@
    do
        if ! url=$(2>/dev/null curl -fs "$baseurl$i/pdf" | \
            gawk -v 'RS=http-equiv="[rR]efresh".*[0-9 ;]*[uU][rR][lL]=' -F '"' \
            '$1 ~ /^http.*[.]pdf/{a=$1;exit}
            END{if(a){print a} else{exit 1}}')
        then
            >&2 echo "unable to extract url for $i"
            continue
        fi
        if [[ -e ${directory:+$directory[-1]/}${${url##*/}%%\?*} ]]
        then
            >&2 echo "looks like $i was already downloaded to ${directory:+$directory[-1]/}${${url##*/}%%\?*}"
            continue
        fi
        curl -f --create-dirs -o ${directory:+$directory[-1]/}${${url##*/}%%\?*} $url
    done
}
if ! zparseopts -D 'd:=directory'
then
    return 1
fi
if [[ -z $@ ]]
then
    >&2 printf '\t%s\n' \
        "[-d DIRECTORY]" \
        "[NUMBER] ... download issue by number" \
        "[latest] download most recent issue" \
        "[all] download all issues" \
        "[book:list] list all books" \
        "[book:WORD] ... download books matching WORD" \
        "[book:-WORD] ... don't download books matching WORD" \
        "[book:all] download all books" \
        "... no args specified, nothing to do ... exiting"
    return 0
fi
if [[ -n $directory ]]
then
    if ! mkdir -p $directory[-1]
    then
        return 1
    fi
    >&2 echo "files will be saved in $directory[-1]"
fi
for (( i=1; i<=${#@}; i++ ))
do
    case ${@[i]} in
        (all) all=all ;;            #download all standard issues
        (latest) latest=1 ;;            #download most recent issue
        (book:list) list_books=list ;;  #print a list of books
        (book:all) all_books=all ;;     #download all books
        (book:[[:alnum:]-]##) book+=( ${@[i]#*:} ) ;;   #download matching books (or books not matching if book:- is used)
        ([0-9]##) standard+=${@[i]} ;;          #download standard issue by number
        (*) ignore+=${@[i]} ;;          #tell user about unused args
    esac
done
if [[ -n $list_books || -n $all_books || -n $book ]]    #book argument was specified - get books
then
    books ${list_books:-${all_books:-$book}}
fi
if [[ -n $standard || -n $latest || -n $all ]]      #issue args - get issues
then
    issues $all $standard
fi
if [[ -n $ignore ]]
then
    >&2 printf '\t%s\n' "the following arguments were ignored:" $ignore
fi
return 0

스크립트 끝에는 사용법을 설명하는 몇 가지 설명이 있습니다.

  • 유효한 질문 관련 인수는 다음과 같습니다. latest또는 alla NUMBER– 예를 들어 범위를 지정하기 위해 스크립트를 호출할 때 셸 확장을 사용할 수 있습니다. bash/zsh에서 이슈 12~15를 다운로드하려면 {12..15}12~15번으로 확장되어야 함 을 지정하세요.
  • 유효한 도서 관련 매개변수에는 book:list, book:all또는 book:WORD일치, book:-WORD제외 등이 있습니다. book:{begin,-3rd}"Book 3"을 제외한 "Beginner" 시리즈의 책이 다운로드됩니다.
  • -d DIR지정된 디렉터리에 파일을 출력하는 옵션
  • 매개변수의 모든 조합은 유효해야 하며 유효하지 않은 매개변수는 무시됩니다.
  • 다운로드를 재개하지 않고도 -C -해당 옵션을 최종 명령에 추가하고 이전 파일 충돌 테스트에서 제거하면 됩니다.curlget_pdfs()continue

제가 놓친 부분이 있을 수 있습니다. 사용에 따른 책임은 본인에게 있습니다!


HTML 리디렉션을 "따르기" 위해 컬을 사용하는 예는 위 함수에서 찾을 수 있습니다 get_pdfs().

url=$(curl -fs <url_of_document_using_html_redirect> | \
    gawk -v \
    'RS=http-equiv="[rR]efresh" *content="[0-9 ;]*[uU][rR][lL]=' \
    -F '"' \
    '/^http/{print $1;exit}')

그러면 우리는 다운로드할 수 있어야 합니다"$url"

관련 정보