2013-05-10 4 views
1

나는 BeautifulSoup로 웹 사이트를 긁어 내려고하고있다. 문제의 사이트에 로그인해야합니다. 제 코드를 살펴보십시오. 로그인해야하는 웹 사이트 스크랩

from bs4 import BeautifulSoup as bs 
import requests 
import sys 

user = 'user' 
password = 'pass' 

# Url to login page 
url = 'main url' 

# Starts a session 
session = requests.session(config={'verbose': sys.stderr}) 

login_data = { 
'loginuser': user, 
'loginpswd': password, 
'submit': 'login', 
} 

r = session.post(url, data=login_data) 

# Accessing a page to scrape 
r = session.get('specific url') 
soup = bs(r.content) 

나는 나는 그것이 유효해야합니다 생각하지만, 내가 로그 아웃 된 것처럼 인쇄 된 내용이 여전히 SO 그래서에서, 여기에 몇 가지 스레드를 본 후에이 코드를 함께했다.

나는이 코드를 실행

,이 인쇄됩니다 :

2013-05-10T22:49:45.882000 POST >the main url to login< 
2013-05-10T22:49:46.676000 GET >error page of the main url page as if the logging in failed< 
2013-05-10T22:49:46.761000 GET >the specific url< 

물론, 로그인 정보가 정확합니다. 도움 사람이 필요합니다.

@EDIT

어떻게 위로 헤더를 구현하는 것이?

opener = urllib2.build_opener() 
opener.addheaders = [('User-agent', 'Mozilla/5.0')] 

답변

3

우선 1.2.0보다 오래된 버전은 사용하지 않아야합니다. 버그를 발견하면 지원하지 않을 것입니다.

둘째, 당신이 가능성이 찾고있는 것은 이것이다 :

import requests 
from requests.packages.urllib3 import add_stderr_logger 

add_stderr_logger() 
s = requests.Session() 

s.headers['User-Agent'] = 'Mozilla/5.0' 

# after examining the HTML of the website you're trying to log into 
# set name_form to the name of the form element that contains the name and 
# set password_form to the name of the form element that will contain the password 
login = {name_form: username, password_form: password} 
login_response = s.post(url, data=login) 
for r in login_response.history: 
    if r.status_code == 401: # 401 means authentication failed 
     sys.exit(1) # abort 

pdf_response = s.get(pdf_url) # Your cookies and headers are automatically included 

내가 당신을 도울 수있는 코드를 댓글을 달았습니다. HTTP Basic Auth 사용에 대한 @ FastTurtle의 제안을 시도해 볼 수도 있지만, 처음에 양식에 게시하려는 경우 위에서 설명한대로 계속 시도 할 수 있습니다. 또한 loginuserloginpswd이 올바른 양식 요소 이름인지 확인하십시오. 그렇지 않다면 잠재적 인 문제 일 수 있습니다 .b

1

requests 모듈은 여러 인증 유형을 지원합니다. 행운을 빌어 당신이 분석하려고하는 웹 사이트는 HTTP 기본 인증을 사용합니다.이 경우 자격 증명을 보내는 것이 매우 쉽습니다.

이 예제는 the requests website에서 가져온 것입니다. here 및 헤더 here을 사용하여 인증에 대한 자세한 내용을 볼 수 있습니다.

s = requests.Session() 
s.auth = ('user', 'pass') 
s.headers.update({'x-test': 'true'}) 

# both 'x-test' and 'x-test2' are sent 
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})