Skip to main content
 首页 » 编程设计

python之Json,抓取到网页之python

2024年12月31日12soundcode

我正在使用 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'>