前言

这篇文章主要讲述正则表达式中对于json的提取。

一、代码

#根着视频学习的代码,记录分享一下
#1.导入相关模块
import requests
import re
from bs4 import BeautifulSoup

#2.发送请求,获取疫情首页内容
response = requests.get('https://ncov.dxy/ncovh5/view/pneumonia')
home_page=response.content.decode()
#print(home_page)
#3.使用BeautifulSoup提取疫情数据
soup = BeautifulSoup(home_page,'lxml')
script=soup.find(id='getListByCountryTypeService2true')
text=script.text
#print(text)

#使用正则表达式,提取json字符串
json_str=re.findall(r'\[.+\]',text)[0]
print(json_str)

总结

代码运行成功,就成功提取了json字符串。

更多推荐

爬虫学习日志7--正则表达式提取json字符串