python - Json,抓取到网页 - python
问题描述
我正在使用python中的请求和beautifulsoup库抓取某些网页
所以我在这个简单的代码中得到了我想要的元素
<script>
data = {'user':{'id':1,'name':'joe','age':18,'email':'joe@hotmail.com'}}
</script>
所以我想在变量中获取电子邮件值,但整个元素又回到列表中,当我指定该标签的文本时,我无法将它放入 json 它给我列中的错误,所以知道吗?我会很感激任何帮助
解决方案
一些简单的东西,也许会对你有所帮助。
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'>
推荐阅读
- python - 如何在 html 文件中编写 python 代码?我创建的所有 html 文件都在 /templates 文件夹中,如烧瓶文档中所述
- php - 如何在具有数组字段的弹性搜索中进行搜索?
- python - 如何使用fill_between按月创建最小-最大图
- rpm - 如何在规范文件中创建多行摘要?
- javascript - Safari getDisplayMedia 必须从用户手势处理程序中调用
- css - 即使使用 KeyboardAvoidingView,React Native Sticky Footer Input 也被键盘覆盖
- testing - TestCafe:如何让 TestCafe 在所有固定装置之前只运行一次应用程序代码
- python - DataFrame 更新未保存到文件
- spring-boot - gradle 连续构建技巧在 docker 容器中不起作用
- azure - 新对象:找不到类型 [Microsoft.Open.AzureAD.Model.DomainFederationSettings]:验证程序集