0
我如何找到價值例如上下文 with beautifulsoup?我如何通過Beautifulsoup訪問此信息?
這就是我在Python中打印Beautiful var時得到的一些結果。
<script>
(function (root) {
root['__playIT'] = {"context":{"dispatcher":{"stores"}
}(this));
</script>
我如何找到價值例如上下文 with beautifulsoup?我如何通過Beautifulsoup訪問此信息?
這就是我在Python中打印Beautiful var時得到的一些結果。
<script>
(function (root) {
root['__playIT'] = {"context":{"dispatcher":{"stores"}
}(this));
</script>
隨着BeautifulSoup
,你只能找到所需的script
元素。然後,提取實際context
值,你可以使用,例如,正則表達式:
import re
from bs4 import BeautifulSoup
data = """
<script>
(function (root) {
root['__playIT'] = {"context":{"dispatcher":{"stores"}
}(this));
</script>"""
soup = BeautifulSoup(data, "html.parser")
pattern = re.compile(r'"context":(\{.*?)$', re.MULTILINE | re.DOTALL)
script = soup.find("script", text=pattern)
result = pattern.search(script.text).group(1)
print(result)
打印:
{"dispatcher":{"stores"}
需要注意的是,如果該值會一直有效的JSON字符串,可以用json.loads()
加載它。
嗨!感謝您的快速回答! 當我試圖運行你的代碼是收到此錯誤信息: 結果= pattern.search(script.text)。集團(1) AttributeError的:「NoneType」對象有沒有屬性「文本」 – gel
@gel好,這是我提供了一個我一直在執行的完整代碼的原因之一。我認爲您的實際腳本值與您在問題中發佈的值不同。 – alecxe
這是您嘗試執行的完整代碼。我沒有改變任何東西。 編輯:如果這有幫助:https://codeshare.io/noIKd – gel