[英]Web scraping with python, request.json() shows status_code of 200 but can not extract json data
[英]Python web scraping with requests - status code 200, but no successful login
准備問我的第一個問題和編程新手,所以請耐心等待:我正在嘗試使用 Python 和requests
-library 進行一些有趣的網絡抓取。 但是,我無法成功登錄該網站。 這是我嘗試登錄的網站上表單的 html 代碼:
<body class="login"><div class="wrapper">
<div class="wrapper_forms">
<!-- Login Form -->
<form class="login" action="?" method="post">
<fieldset>
<legend>Login</legend>
<label for="login_username">Benutzername:</label>
<input id="login_username" type="text" name="username" autofocus="autofocus" /><em>*</em><br>
<label for="login_password">Passwort:</label>
<input id="login_password" type="password" name="password" /><em>*</em><br>
<em>* required</em><br>
<input type="hidden" name="form" value="login" />
<input id="screen_width" type="hidden" name="screen_width" value="" />
<input type="submit" value="Login" />
<br><a class="pw_reset" href="?action=pw_reset">Passwort vergessen</a>
<br>
</fieldset>
</form>
這是我的代碼的縮寫版本。 我還對我為了可讀性而排除的 get 和 post 請求的響應對象進行了一些額外的檢查。 該站點當前沒有有效的 SSL 證書,因此verify = False
參數。
from bs4 import BeautifulSoup
import requests
# Start session
session = requests.Session()
# payload
payload = {'username':'****',
'password':'****',
'form':'login',
'screen_width':'1920'}
# variables
login = "https://altklausurendb.de/login.php"
dest = "https://altklausurendb.de/index.php"
# initial get request to retrieve cookies and headers
s = session.get(login, verify = False)
cookies = s.cookies.get_dict()
headers = s.headers
# distribute payload
r1 = session.post(login, data = payload, cookies = cookies, headers = headers, verify = False)
#download content of destination site
r2 = session.get(dest, cookies = cookies, verify = False)
soup = BeautifulSoup(r2.text, 'html.parser')
print(soup)
打印函數的輸出給了我上面的 html 表單,而不是https://altklausurendb.de/index.php
的內容,后者是第二個GET
請求的dest
變量。
在閱讀了這里、reddit 和 WWW 的其他內容后,我自己嘗試過的事情:
POST
請求中顯式傳遞 cookie 和標頭即可運行它(顯而易見)POST
請求,使用網絡點擊下的 Chrome 開發工具。 甚至在腳本的單獨版本中手動復制標頭,以防requests
header
函數以某種方式提供錯誤的標頭。GET
和POST
請求創建的response
運行所有檢查,有趣的是,無論我在字典中提供什么用戶名和密碼,狀態代碼始終為200
--> 這讓我懷疑,如果網站沒有以403
響應錯誤憑據,則POST
請求未正確提交。 我看到某些網站在<input type="submit">
語句中也有一個name
-variable,您必須將其傳遞給字典。 然而,這個網站似乎沒有它,基本上這就是我現在卡住的地方。
如果他們想自己重現腳本的行為,我願意將我在網站上創建的測試帳戶的憑據發送給某人。
感謝您的耐心等待,我知道網絡抓取問題並不是最喜歡的問題,我感謝您的幫助!
扔掉所有這些,得到硒模塊。 BS4 適合抓取 HTML,但如果您要抓取動態頁面,則需要 selenium。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.