Python의 요청 모듈을 사용하여 웹 사이트에 "로그인"하는 방법은 무엇입니까?
Python의 Requests 모듈을 사용하여 웹 사이트에 로그인하라는 요청을 게시하려고하지만 실제로 작동하지 않습니다. 나는 이것에 익숙하지 않아 ... 내 사용자 이름 및 암호 쿠키를 만들어야하는지 또는 내가 찾은 (??) HTTP 인증 유형을 만들어야하는지 알 수 없습니다.
from pyquery import PyQuery
import requests
url = 'http://www.locationary.com/home/index2.jsp'
그래서 지금은 "포스트"와 쿠키를 사용해야한다고 생각합니다 ..
ck = {'inUserName': 'USERNAME/EMAIL', 'inUserPass': 'PASSWORD'}
r = requests.post(url, cookies=ck)
content = r.text
q = PyQuery(content)
title = q("title").text()
print title
쿠키를 잘못하고 있다는 느낌이 들어요 ... 모르겠어요.
제대로 로그인되지 않으면 홈 페이지 제목이 "Locationary.com"에 나와야하고 그렇지 않으면 "홈 페이지"가되어야합니다.
요청과 쿠키에 대한 몇 가지 사항을 설명해 주시고 도움을 주시면 감사하겠습니다. :디
감사.
... 아직 작동하지 않았습니다. 좋아요 ... 로그인하기 전에 홈페이지 HTML이 말하는 내용입니다.
</td><td><img src="http://www.locationary.com/img/LocationaryImgs/icons/txt_email.gif"> </td>
<td><input class="Data_Entry_Field_Login" type="text" name="inUserName" id="inUserName" size="25"></td>
<td><img src="http://www.locationary.com/img/LocationaryImgs/icons/txt_password.gif"> </td>
<td><input class="Data_Entry_Field_Login" type="password" name="inUserPass" id="inUserPass"></td>
그래서 제대로하고 있다고 생각하지만 출력은 여전히 "Locationary.com"입니다.
두 번째 편집 :
오랫동안 로그인 상태를 유지하고 싶고 해당 도메인에서 페이지를 요청할 때마다 콘텐츠가 로그인 된 것처럼 표시되기를 원합니다.
원하는 정보가 페이지에 있으면 로그인 후 바로 연결됩니다.
대신 python-requests 문서 에서와 같이 ck
변수 payload
를 호출 할 수 있습니다 .
payload = {'inUserName': 'USERNAME/EMAIL', 'inUserPass': 'PASSWORD'}
url = 'http://www.locationary.com/home/index2.jsp'
requests.post(url, data=payload)
그렇지 않으면...
아래 https://stackoverflow.com/a/17633072/111362를 참조 하십시오 .
나는 당신이 다른 해결책을 찾았다는 것을 알고 있지만, 같은 질문을 찾는 저와 같은 사람들에게는 다음과 같은 요청을 통해 얻을 수 있습니다.
먼저 Marcus가 한 것처럼 로그인 양식의 소스를 확인하여 양식이 게시되는 URL과 사용자 이름 및 비밀번호 필드의 이름 속성이라는 세 가지 정보를 얻습니다. 그의 예에서는 inUserName 및 inUserPass입니다.
그런 다음 requests.Session()
인스턴스를 사용 하여 로그인 세부 정보를 페이로드로 사용하여 로그인 URL에 게시 요청을 할 수 있습니다 . 세션 인스턴스에서 요청을 만드는 것은 일반적으로 요청을 사용하는 것과 본질적으로 동일하며 단순히 지속성을 추가하여 쿠키 등을 저장하고 사용할 수 있습니다.
로그인 시도가 성공했다고 가정하면 세션 인스턴스를 사용하여 사이트에 추가 요청을 할 수 있습니다. 귀하를 식별하는 쿠키는 요청을 승인하는 데 사용됩니다.
예
import requests
# Fill in your details here to be posted to the login form.
payload = {
'inUserName': 'username',
'inUserPass': 'password'
}
# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
p = s.post('LOGIN_URL', data=payload)
# print the html returned or something more intelligent to see if it's a successful login page.
print p.text
# An authorised request.
r = s.get('A protected web page url')
print r.text
# etc...
Let me try to make it simple, suppose URL of the site is http://example.com/ and let's suppose you need to sign up by filling username and password, so we go to the login page say http://example.com/login.php now and view it's source code and search for the action URL it will be in form tag something like
<form name="loginform" method="post" action="userinfo.php">
now take userinfo.php to make absolute URL which will be 'http://example.com/userinfo.php', now run a simple python script
import requests
url = 'http://example.com/userinfo.php'
values = {'username': 'user',
'password': 'pass'}
r = requests.post(url, data=values)
print r.content
I Hope that this helps someone somewhere someday.
Find out the name of the inputs used on the websites form for usernames <...name=username.../>
and passwords <...name=password../>
and replace them in the script below. Also replace the URL to point at the desired site to log into.
login.py
#!/usr/bin/env python
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
payload = { 'username': 'user@email.com', 'password': 'blahblahsecretpassw0rd' }
url = 'https://website.com/login.html'
requests.post(url, data=payload, verify=False)
The use of disable_warnings(InsecureRequestWarning)
will silence any output from the script when trying to log into sites with unverified SSL certificates.
Extra:
To run this script from the command line on a UNIX based system place it in a directory, i.e. home/scripts
and add this directory to your path in ~/.bash_profile
or a similar file used by the terminal.
# Custom scripts
export CUSTOM_SCRIPTS=home/scripts
export PATH=$CUSTOM_SCRIPTS:$PATH
Then create a link to this python script inside home/scripts/login.py
ln -s ~/home/scripts/login.py ~/home/scripts/login
Close your terminal, start a new one, run login
The requests.Session()
solution assisted with logging into a form with CSRF Protection (as used in Flask-WTF forms). Check if a csrf_token
is required as a hidden field and add it to the payload with the username and password:
import requests
from bs4 import BeautifulSoup
payload = {
'email': 'email@example.com',
'password': 'passw0rd'
}
with requests.Session() as sess:
res = sess.get(server_name + '/signin')
signin = BeautifulSoup(res._content, 'html.parser')
payload['csrf_token'] = signin.find('input', id='csrf_token')['value']
res = sess.post(server_name + '/auth/login', data=payload)
'Programing' 카테고리의 다른 글
IOError : [Errno 32] 깨진 파이프 : Python (0) | 2020.10.11 |
---|---|
디렉토리를 쓰기 가능하게하려면 어떻게해야합니까? (0) | 2020.10.11 |
iOS : 프로그래밍 방식으로 UILabel의 글꼴 크기 설정 (0) | 2020.10.11 |
해결 실패 : com.android.support:appcompat-v7:26.0.0 (0) | 2020.10.11 |
Windows에서 열려있는 모든 명명 된 파이프 목록을 얻으려면 어떻게해야합니까? (0) | 2020.10.11 |