[英]How do I scrape the login token generated by JS in Python?
我必須抓取一個需要登錄令牌的網站。 稍后將通過 JS 替換該值。
document.getElementById('token').value='aa5fedc5decbba3318deab92ffdfbd55d9a2c09ec81a464351ea449dc726ddd5';
上面的代碼出現在源代碼中的</html>
標記之后。 像這樣:
</body>
</html>
<script>
document.getElementById('token').value='aa5fedc5decbba3318deab92ffdfbd55d9a2c09ec81a464351ea449dc726ddd5';
</script>
我必須復制此值並通過 http 請求將其發布到 URL 以使請求被接受。
但我無法得到這個值。 當我通過 python 請求庫發送請求時, </html>
標記后的代碼不可見。
我的 python 代碼在這里:
import requests
from bs4 import BeautifulSoup
session_requests = requests.session()
html = session_requests.get("http://lms.uaf.edu.pk/login/index.php")
html = html.text
soup = BeautifulSoup(html, "lxml")
print(soup)
如何通過 python 獲取登錄令牌?
您的代碼不起作用的原因是,BeautifulSoup 在</html>
之后跳過任何 html 代碼(這基本上關閉了文檔),因此它只解析<html>
<script>
內的所有內容,並作為帶有替換登錄令牌的 JavaScript 位於結束</html>
標記之后,它不會被 BeautifulSoup 解析,因此您無法獲取它。 在瀏覽器中(我在 FireFox 上對其進行了測試),結束</html>
標記之后的所有內容都移到了文檔正文中,這就是為什么當您在瀏覽器中查看站點時登錄令牌會正確顯示的原因。 為此,您應該將 BeautifulSoup 放在一邊,只需使用普通的 Python (可讀版本):
import requests
html = requests.get('http://lms.uaf.edu.pk/login/index.php').text # get the html
token_begin = html.find("document.getElementById('token').value='") + len("document.getElementById('token').value='") # find the start of the login token
token_end = html[token_begin:].find("'") # find the end of the login token
token = html[token_begin:token_end]
以下代碼成功從您的網站獲取登錄令牌:
import requests
session_requests = requests.session()
html = session_requests.get("http://lms.uaf.edu.pk/login/index.php")
html = html.text
a = html.split("document.getElementById(\'token\').value=\'")[1]
b = a.split("'")[0]
我會 go 與response.text
的直接正則表達式,但是,值得知道的是,您可以保留該內容,至少對於我遇到的所有 html 解析器,通過包裝在一組外部body
標簽中。 不提倡這種方法,盡管在某些語言中它對於獲取 HEAD 中的數據非常有用,否則當輸入 DOM 文檔的 body.innerHTML 時會被剝離。
import requests
from bs4 import BeautifulSoup as bs
r = requests.get('http://lms.uaf.edu.pk/login/index.php')
soup = bs('<body>' + r.text + '</body>', 'lxml')
print(soup.select('script')[-1].string.split("'")[-2])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.