首页 > 解决方案 > Json,抓取到网页 - python

问题描述

我正在使用python中的请求和beautifulsoup库抓取某些网页

所以我在这个简单的代码中得到了我想要的元素

<script>
data = {'user':{'id':1,'name':'joe','age':18,'email':'joe@hotmail.com'}}
</script>

所以我想在变量中获取电子邮件值,但整个元素又回到列表中,当我指定该标签的文本时,我无法将它放入 json 它给我列中的错误,所以知道吗?我会很感激任何帮助

标签: pythonjsondictionaryweb-scraping

解决方案


一些简单的东西,也许会对你有所帮助。

import json
from bs4 import BeautifulSoup

html = """
<script>
data = {'user':{'id':1,'name':'joe','age':18,'email':'joe@hotmail.com'}}
</script>
"""

soup = BeautifulSoup(html, 'html.parser')
# slices [7:] mean that we ignore the `data = `
# and replace the single quotes to double quotes for json.loads()
json_data = json.loads(soup.find('script').text.strip()[7:].replace("'", '"'))
print(json_data)
print(type(json_data))

输出

{'user': {'id': 1, 'name': 'joe', 'age': 18, 'email': 'joe@hotmail.com'}}
<class 'dict'>

推荐阅读