Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

PowerShell Invoke-WebRequest로 웹사이트 링크 추출하는 방법

PowerShell을 사용해 웹사이트에 포함된 링크를 가져오려면, 먼저 Invoke-WebRequest cmdlet으로 해당 웹페이지의 데이터를 불러와야 합니다.

$req = Invoke-WebRequest -uri "https://theautomationcode.com"
$req

출력 결과

웹페이지 전체 데이터가 정상적으로 반환되면, 이제 링크 정보만 별도로 추출할 수 있습니다.

링크만 가져오려면 Links 속성을 사용하면 됩니다. 이 속성 안에는 아래 출력 결과에서 확인할 수 있듯이 InnerHTML, InnerText, href 등 다양한 하위 속성들이 함께 포함되어 있습니다.

$req = Invoke-WebRequest -uri "https://theautomationcode.com"
$req.Links

출력 결과

innerHTML : Scripts
innerText : Scripts
outerHTML : <A href="https://theautomationcode.com/scripts/">Scripts</A>
outerText : Scripts
tagName   : A
href      : https://theautomationcode.com/scripts/  

여기서 우리가 실제로 필요한 것은 링크 주소 자체이므로, href 속성만 선택적으로 추출하면 됩니다.

$req.Links | Select -ExpandProperty href

출력 결과

https://theautomationcode.com/2020/11/
https://theautomationcode.com/author/chiragce17/
https://theautomationcode.com/category/powershell/
https://theautomationcode.com/category/troubleshooting/

Select -ExpandProperty hrefSelect-Object -ExpandProperty의 축약형으로, 객체 배열에서 특정 속성값만 깔끔하게 펼쳐서 문자열 목록 형태로 반환해 줍니다. 이처럼 Invoke-WebRequest와 Links 속성을 조합하면 별도의 외부 도구 없이 PowerShell만으로 웹사이트의 모든 링크를 간편하게 수집할 수 있습니다.