문제 설명
파이썬을 사용하여 웹사이트에서 내부 링크만 크롤링 (Crawl only internal links from a website using python)
사이트의 내부 링크만 처리하는 크롤러를 작성하려고 합니다. 나는 python 2.7, 아름다운 수프 및 요청을 사용하고 있으며 모든 내부 링크(절대 및 친척)가 필요합니다.
내 클라이언트가 사이트에 대한 크롤러를 요청했지만 내부 링크만 크롤링하기를 원합니다. . jpg/png/gif 및 기타 URL을 무시해야 하므로 페이지만 처리합니다.
import re, request
from bs4 import BeautifulSoup
def processUrl(url):
if not url in checkedUrls:
try:
if 'text/html' in requests.head(url).headers['Content‑Type']:
req=requests.get(url)
if req.status_code==200:
print url
checkedUrls.append(url)
html=BeautifulSoup(req.text,'html.parser')
pages=html.find_all('a')
for page in pages:
url=page.get('href')
processUrl(url)
except:
pass
checekdUrls=[]
url='http://sampleurl.com'
processUrl(url)
참조 솔루션
방법 1:
Here's your code, with the addition of the logic i commented above.
import re, request
from bs4 import BeautifulSoup
def processUrl(url, domain, checkedUrls=[]):
if domain not in url:
return checkedUrls
if not url in checkedUrls:
try:
if 'text/html' in requests.head(url).headers['Content‑Type']:
req=requests.get(url)
if req.status_code==200:
print url
checkedUrls.append(url)
html=BeautifulSoup(req.text,'html.parser')
pages=html.find_all('a')
for page in pages:
url=page.get('href')
processUrl(url)
except:
pass
return checkedUrls
checekdUrls=[]
domain = 'sampleurl.com'
url='http://sampleurl.com'
checkedUrls = processUrl(url, domain, checkedUrls)
(by Carlos Castillo、kerwei)