有没有一种简单的方法可以将内容从 <pre> 标签获取到 pandas 数据框?
Is there an easy way to get the content from a <pre> tag to a pandas dataframe?
我试图将 pre 标签的内容传递给 pandas 数据框,但我无法做到,这是我目前所拥有的:
import requests,pandas
from bs4 import BeautifulSoup
#url
url='http://weather.uwyo.edu/cgi-bin/sounding?region=samer&TYPE=TEXT%3ALIST&YEAR=2019&MONTH=09&FROM=2712&TO=2712&STNM=80222'
peticion=requests.get(url)
soup=BeautifulSoup(peticion.content,"html.parser")
#get only the pre content I want
all=soup.select("pre")[0]
#write the content in a text file
with open('sound','w') as f:
f.write(all.text)
#read it
df = pandas.read_csv('sound')
df
我得到了一个非结构化的数据帧,因为我必须使用多个 url 来执行此操作,所以我宁愿在第 12 行之后直接传递数据,而无需编写文件。
this is the dataframe I get
它是固定宽度的文本,因此您需要通过拆分 '\n' 来生成行,然后使用固定宽度值来生成列。您可以使用 csv 来节省开销,但您需要一个数据框。
import pandas as pd
import requests
from bs4 import BeautifulSoup as bs
r = requests.get('http://weather.uwyo.edu/cgi-bin/sounding?region=samer&TYPE=TEXT%3ALIST&YEAR=2019&MONTH=09&FROM=2712&TO=2712&STNM=80222')
soup = bs(r.content, 'lxml')
pre = soup.select_one('pre').text
results = []
for line in pre.split('\n')[1:-1]:
if '--' not in line:
row = [line[i:i+7].strip() for i in range(0, len(line), 7)]
results.append(row)
df = pd.DataFrame(results)
print(df)
我试图将 pre 标签的内容传递给 pandas 数据框,但我无法做到,这是我目前所拥有的:
import requests,pandas
from bs4 import BeautifulSoup
#url
url='http://weather.uwyo.edu/cgi-bin/sounding?region=samer&TYPE=TEXT%3ALIST&YEAR=2019&MONTH=09&FROM=2712&TO=2712&STNM=80222'
peticion=requests.get(url)
soup=BeautifulSoup(peticion.content,"html.parser")
#get only the pre content I want
all=soup.select("pre")[0]
#write the content in a text file
with open('sound','w') as f:
f.write(all.text)
#read it
df = pandas.read_csv('sound')
df
我得到了一个非结构化的数据帧,因为我必须使用多个 url 来执行此操作,所以我宁愿在第 12 行之后直接传递数据,而无需编写文件。
this is the dataframe I get
它是固定宽度的文本,因此您需要通过拆分 '\n' 来生成行,然后使用固定宽度值来生成列。您可以使用 csv 来节省开销,但您需要一个数据框。
import pandas as pd
import requests
from bs4 import BeautifulSoup as bs
r = requests.get('http://weather.uwyo.edu/cgi-bin/sounding?region=samer&TYPE=TEXT%3ALIST&YEAR=2019&MONTH=09&FROM=2712&TO=2712&STNM=80222')
soup = bs(r.content, 'lxml')
pre = soup.select_one('pre').text
results = []
for line in pre.split('\n')[1:-1]:
if '--' not in line:
row = [line[i:i+7].strip() for i in range(0, len(line), 7)]
results.append(row)
df = pd.DataFrame(results)
print(df)