좋아요, 이것은 requests
및 BeautifulSoup
과 관련하여 흥미로운 작업이었습니다.
un.org
및 daccess-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)
당신은 아마 더 읽기 쉽고 재사용하기 위해 기능에 코드의 별도의 블록을 추출해야합니다
여기에 전체 코드입니다.
참고로이 모든 것은 selenium
의 Ghost.py
을 사용하여 실제 브라우저를 통해 더 쉽게 수행 할 수 있습니다.
희망이 있습니다.
도움 주셔서 감사합니다. 끝에'Ghost.py'를 언급했을 때, 당신은'GhostDriver'를 의미 했습니까? 나는 봤기 때문에 셀레늄과 Ghost.py를 결합하는 방법에 대해서는별로 알지 못했습니다. 더 많은 정보를 제공해 주시겠습니까? – Darwin