【问题标题】:How do I convert a list with one element into a list with many elements in python如何在python中将具有一个元素的列表转换为具有多个元素的列表
【发布时间】:2021-08-03 07:15:44
【问题描述】:

我正在尝试创建一个元素中的列表。因此我需要将一个元素转换为可能:包含日期。

代码:

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)

【问题讨论】:

  • 你能显示有问题的变量的值,以及你的预期输出吗?这将使这个例子更容易理解。您甚至可以删除样本的第一部分,然后是关于您如何获得数据的第一部分。
  • 我不明白你想做什么。更好地展示示例数据,以及您获得的结果以及您的期望。
  • 您似乎从 JavaScript 获取数据,并且您有类似于 JSON 的内容,因此您可以使用模块 json 将其转换为 Python 列表。

标签: python list split element


【解决方案1】:

您尝试从 categories: [] 之间的 JavaScript 数据 (Highcharts) 获取值 - 因此您可以使用 split() 获取这部分。如果您稍后添加 [] - "[" + string + "]" - 那么您将拥有带有 JSON 数据的字符串,您可以使用模块 json 将其转换为列表

这给出了包含 535 个元素的列表

import requests
from bs4 import BeautifulSoup
import json

url = "https://www.worldometers.info/coronavirus/country/us/"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")

results = soup.find_all("div", {"class": "col-md-12"})

string = results[4].find('script').string

# remove string before dates
substring = string.split("categories: [")[1]

# remove string after dates
substring = substring.split("]")[0]

# create back string with list
substring = "[" + substring + "]"

#print(substring)

# convert string with JSON data into Python list
dates = json.loads(substring)

print('len(dates):', len(dates))

顺便说一句:

大约 1.5 年前我对同一页面的回答:

Web scrape coronavirus interactive plots

我还在我的博客上找到了代码:

Scraping: How to get data from interactive plot created with HighCharts

但我宁愿尝试从 GitHub CSSEGISandData / COVID-19 获取 CSV 文件并将其加载到 pandas 并计算 pandas 中的所有值。而且我想我很久以前在某个答案中描述了它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 2021-10-04
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多