【发布时间】:2021-03-05 16:05:30
【问题描述】:
我真的很难从网页中提取一些数据点到熊猫数据框中。
我对提取值38.31 和-0.06 很感兴趣。
如果我使用name_y = soup.find(id='current'),我会得到以下结果:
<div id="current">
<b>Current<span class="currentTitle">
S&P 500 PE Ratio</span>:</b>
38.31
<span class="neg">
-0.06
(-0.16%)
</span>
<div id="timestamp">
10:39 AM EST, Fri Mar 5
</div>
</div>
我已经尝试过name_y = soup.find(id='current').text 和name_y = soup.find(id='current').b.next_sibling,但它仍然给我一些噪音。
当前结果:
0 \n38.37\n\n\n\n\n\n
dtype: object
预期的最终结果:
print(df)
PE Change
0 38.31 -0.06
完整代码:
import requests
from bs4 import BeautifulSoup
import re
import pandas as pd
url = 'https://www.multpl.com/s-p-500-pe-ratio'
res = requests.get(url)
html = res.text
soup = BeautifulSoup(html, 'html.parser' )
# name_y = soup.find(id='current')
df = pd.Series(soup.find(id='current').b.next_sibling)
print(df)
【问题讨论】:
标签: python pandas web-scraping beautifulsoup