【问题标题】:Get specific text into a pandas dataframe, webscraping with BeautifulSoup将特定文本放入 pandas 数据框中,使用 BeautifulSoup 进行网络抓取
【发布时间】: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&amp;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').textname_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


    【解决方案1】:

    您可以使用.strip() 删除\n 字符。

    soup.find(id='current').b.next_sibling.strip()
    

    完整代码:

    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')
    
    change = soup.find(id='current').select_one('.pos, .neg').get_text().split("(")[0].strip()
    pe = soup.find(id='current').b.next_sibling.strip()
    
    df = pd.DataFrame([({'PE': pe, 'Change': change})])
    print(df)

    输出:

          PE Change
    0  38.11  -0.26
    

    【讨论】:

    • 感谢您提供出色而清晰的答案,非常感谢:)!!
    • 好吧,这真是令人印象深刻,特别感谢@QHarr!你帮了我很多次,才真正感激。我的肮脏解决方案是做一个 try/except 语句,但这样更干净更好:)
    【解决方案2】:

    您可以检查此代码是否有效:

    from bs4 import BeautifulSoup as soup
    import requests
    
    url = 'https://www.multpl.com/s-p-500-pe-ratio'
    
    res = requests.get(url)
    html = res.text
    
    c=soup(html, "html.parser")
    name_y = c.find(id='current')
    x = name_y.text
    y = name_y.find("span", {"class":"neg"})
    print(x.split()[5])
    print(y.text.strip().split()[0])
    

    输出

    38.09
    -0.27
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多