Python中如何将仅含单个元素的列表转换为存储多个日期的多元素列表
问题场景
爬取美国新冠疫情数据时,得到仅包含单个元素的列表,该元素内存储了所有拼接的日期字符串,需要转换为包含多个独立日期元素的列表,原有实现代码如下:
import requests from bs4 import BeautifulSoup import ast #gets the dates URL = ("https://www.worldometers.info/coronavirus/country/us/") page = requests.get(URL) soup = BeautifulSoup(page.content, "html.parser") results=soup.find_all("div", {"class": "col-md-12"}) data=results[4] script = data.find('script') string = script.string datesTEMP = string.strip()[292:]#-9268] x=datesTEMP i=0 xaxis=[] count=0 while count<1: if x[i]=="]": count=count+1 else: xaxis.append(x[i]) i=i+1 xaxislength=len(xaxis) xaxis = [''.join(xaxis[0:xaxislength])] print(xaxis)
实现方案
原有代码的问题是提取到完整的日期数组字符串后,手动将其封装为了单元素列表,直接用已导入的ast模块将符合Python列表语法的字符串转为原生列表即可,修改后的完整代码如下:
import requests from bs4 import BeautifulSoup import ast # 获取页面数据 URL = "https://www.worldometers.info/coronavirus/country/us/" page = requests.get(URL) soup = BeautifulSoup(page.content, "html.parser") results = soup.find_all("div", {"class": "col-md-12"}) data = results[4] script = data.find('script') string = script.string datesTEMP = string.strip()[292:] # 提取到第一个]的位置,获取完整的数组字符串 end_idx = datesTEMP.index(']') date_arr_str = datesTEMP[:end_idx + 1] # 直接转成Python原生列表 xaxis = ast.literal_eval(date_arr_str) print(xaxis)
效果说明
修改后输出的xaxis即为每个日期为独立元素的列表,无需额外拆分处理。
内容的提问来源于stack exchange,提问作者Teerath
相关产品推荐
相关产品推荐

