2017-05-03 10 views
0

내 코드를 페이지의 URL을 반환BeautifulSoup로는 참조를 위해 동일한 웹 사이트에 단축

import httplib2 
from bs4 import BeautifulSoup 

h = httplib2.Http('.cache') 
response, content = h.request('http://csb.stanford.edu/class/public/pages/sykes_webdesign/05_simple.html') 
soup = BeautifulSoup(content, "lxml") 
urls = [] 
for tag in soup.findAll('a', href=True): 
    urls.append(tag['href']) 
responses = [] 
contents = [] 
for url in urls: 
    try: 
     response1, content1 = h.request(url) 
     responses.append(response1) 
     contents.append(content1) 
    except: 
     pass 

아이디어는, 나는 웹 페이지의 페이로드를 얻을, 다음 하이퍼 링크 있음을 긁어. 링크 중 하나는 내가 BeautifulSoup로에서지고있어 결과가 그러나 'http://csb.stanford.edu/class/public/index.html'

에 다른 yahoo.com하는 것입니다,이 문제를 제시

>>> urls 
['http://www.yahoo.com/', '../../index.html'] 

스크립트의 두 번째 부분 때문에 단축 URL에서 실행될 수 없습니다. BeautifulSoup이 전체 URL을 검색 할 수있는 방법이 있습니까?

답변

1

웹 페이지의 링크가 실제로 그 양식에 있기 때문입니다. 페이지에서 HTML은 다음과 같습니다이 상대 링크라고

<p>Or let's just link to <a href=../../index.html>another page on this server</a></p>

.

이것을 절대 링크로 변환하려면 urljoin을 표준 라이브러리에서 사용할 수 있습니다.

from urllib.parse import urljoin # Python3 

urljoin('http://csb.stanford.edu/class/public/pages/sykes_webdesign/05_simple.html`, 
     '../../index.html') 
# returns http://csb.stanford.edu/class/public/index.html 
+0

물론 고맙습니다. 예외에 url join 부분을 포함시킬 수 있습니다. –

+0

더 생각해 보면, 나는 신경 쓰지 않을 것입니다. 이것은 하나의 웹 페이지에만 한정된 것이지, 정말 귀찮게 생각할 가치가 없습니다. –