2014-07-19 1 views
3

this과 같은 URL에서 PDF를 자동으로 다운로드하여 UN 해상도 라이브러리를 만들려고합니다.브라우저가 프레임을 지원하지 않는 경우 프레임의 내용을 자동으로 가져 오는 방법 + 직접 프레임에 액세스 할 수 없음

아름 다운 수프를 사용하거나 해당 URL을 열어 기계화하면 "브라우저가 프레임을 지원하지 않습니다."라는 메시지가 나타납니다. 크롬 개발 도구에서 컬링 기능을 사용하면 같은 결과를 얻습니다.

기계화 또는 아름다운 수프를 사용할 때 "브라우저가 프레임을 지원하지 않습니다"라는 표준 조언은 각 개별 프레임의 소스를 따라 가서 해당 프레임을로드하는 것입니다. 하지만 이렇게하면 페이지가 authorized이 아니라는 오류 메시지가 나타납니다.

어떻게하면됩니까? 나는 좀비 또는 유령에서 이것을 시도 할 수 있었다는 것을 나는 짐작한다 그러나 나는 그 (것)들에 익숙하지 않기 때문에 그 공구를 사용하지 않는 것을 선호 할 것입니다.

답변

3

좋아요, 이것은 requestsBeautifulSoup과 관련하여 흥미로운 작업이었습니다.

un.orgdaccess-ods.un.org에 대한 기본 호출 집합이 중요하며 관련 쿠키를 설정합니다. 따라서 requests.Session()을 유지하고 pdf에 액세스하기 전에 여러 URL을 방문해야합니다.

import re 
from urlparse import urljoin 

from bs4 import BeautifulSoup 
import requests 


BASE_URL = 'http://www.un.org/en/ga/search/' 
URL = "http://www.un.org/en/ga/search/view_doc.asp?symbol=A/RES/68/278" 
BASE_ACCESS_URL = 'http://daccess-ods.un.org' 

# start session 
session = requests.Session() 
response = session.get(URL, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36'}) 

# get frame links 
soup = BeautifulSoup(response.text) 
frames = soup.find_all('frame') 
header_link, document_link = [urljoin(BASE_URL, frame.get('src')) for frame in frames] 

# get header 
session.get(header_link, headers={'Referer': URL}) 

# get document html url 
response = session.get(document_link, headers={'Referer': URL}) 
soup = BeautifulSoup(response.text) 

content = soup.find('meta', content=re.compile('URL='))['content'] 
document_html_link = re.search('URL=(.*)', content).group(1) 
document_html_link = urljoin(BASE_ACCESS_URL, document_html_link) 

# follow html link and get the pdf link 
response = session.get(document_html_link) 
soup = BeautifulSoup(response.text) 

# get the real document link 
content = soup.find('meta', content=re.compile('URL='))['content'] 
document_link = re.search('URL=(.*)', content).group(1) 
document_link = urljoin(BASE_ACCESS_URL, document_link) 
print document_link 

# follow the frame link with login and password first - would set the important cookie 
auth_link = soup.find('frame', {'name': 'footer'})['src'] 
session.get(auth_link) 

# download file 
with open('document.pdf', 'wb') as handle: 
    response = session.get(document_link, stream=True) 

    for block in response.iter_content(1024): 
     if not block: 
      break 

     handle.write(block) 

당신은 아마 더 읽기 쉽고 재사용하기 위해 기능에 코드의 별도의 블록을 추출해야합니다

여기에 전체 코드입니다.

참고로이 모든 것은 seleniumGhost.py을 사용하여 실제 브라우저를 통해 더 쉽게 수행 할 수 있습니다.

희망이 있습니다.

+0

도움 주셔서 감사합니다. 끝에'Ghost.py'를 언급했을 때, 당신은'GhostDriver'를 의미 했습니까? 나는 봤기 때문에 셀레늄과 Ghost.py를 결합하는 방법에 대해서는별로 알지 못했습니다. 더 많은 정보를 제공해 주시겠습니까? – Darwin