How to construct data frame from Web Scraping in Python

蓝咒 提交于 2020-04-17 21:58:31

问题


I can fetch data from web page thru web scraping in Python. My data is fetched into a list. But don't know how to transform that list into a data frame. Is there any way I could web scrape and fetch data directly to a df? Here is my code:

import pandas as pd
import requests
from bs4 import BeautifulSoup
from tabulate import tabulate
from pandas import DataFrame
import lxml

# GET the response from the web page using requests library
res = requests.get("https://www.worldometers.info/coronavirus/")

# PARSE and fetch content using BeutifulSoup method of bs4 library
soup = BeautifulSoup(res.content,'lxml')
table = soup.find_all('table')[0]
df = pd.read_html(str(table))

# Here dumping the fetched data to have a look
print( tabulate(df[0], headers='keys', tablefmt='psql') )
print(df[0])

回答1:


import requests
import pandas as pd

r = requests.get("https://www.worldometers.info/coronavirus/")
df = pd.read_html(r.content)[0]

print(type(df))

# <class 'pandas.core.frame.DataFrame'>

df.to_csv("data.csv", index=False)

Output: view




回答2:


Well read_html returns a list of DataFrames (as per documentation), so you have to get the "first" (and only) element of that list.

I would just add at the end (after you call read_html):

df = df[0]

Then you can inspect its info getting:

df.info()

# <class 'pandas.core.frame.DataFrame'>
# RangeIndex: 207 entries, 0 to 206
# Data columns (total 10 columns):
# Country,Other       207 non-null object
# TotalCases          207 non-null int64
# NewCases            59 non-null object
# TotalDeaths         144 non-null float64
# NewDeaths           31 non-null float64
# TotalRecovered      154 non-null float64
# ActiveCases         207 non-null int64
# Serious,Critical    112 non-null float64
# Tot Cases/1M pop    205 non-null float64
# Deaths/1M pop       142 non-null float64
# dtypes: float64(6), int64(2), object(2)
# memory usage: 16.3+ KB


来源:https://stackoverflow.com/questions/61008195/how-to-construct-data-frame-from-web-scraping-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!