【问题标题】:BeautifulSoup webscraping find_all( ): excluded element appended as last elementBeautifulSoup 网页抓取 find_all():排除元素追加为最后一个元素
【发布时间】:2019-07-10 12:12:40
【问题描述】:

我正在尝试从reuters.com 检索财务信息,尤其是公司的长期增长率。我要抓取的元素不会出现在所有网页上,在我的示例中不是 Ticker 'AMCR'。所有抓取的信息都应附加到一个列表中。

如果元素不存在,我已经想办法排除它,但不是将它附加到列表中应该存在的位置,而是将"NaN" 作为最后一个元素而不是在它应该在的地方。

import requests 
from bs4 import BeautifulSoup

LTGRMean = []

tickers = ['MMM','AES','LLY','LOW','PWR','TSCO','YUM','ICE','FB','AAPL','AMCR','FLS','GOOGL','FB','MSFT']
   Ticker LTGRMean
0     MMM     3.70
1     AES     9.00
2     LLY    10.42
3     LOW    13.97
4     PWR    12.53
5    TSCO    11.44
6     YUM    15.08
7     ICE     8.52
8      FB    19.07
9    AAPL    12.00
10   AMCR    19.04
11    FLS    16.14
12  GOOGL    19.07
13     FB    14.80
14   MSFT      NaN

我的个人文本 "not existing" 没有出现。

而不是 AMCR 路透社不提供任何信息,而是设置 FLS (19.04) 的增长率。因此,所有信息都会上移一个索引,NaN 应该出现在 AMCR 旁边。

【问题讨论】:

  • 请分享您的一些代码,您是否在for 循环中使用了正确的range
  • 这是我使用的所有代码。我遗漏的唯一一行是“打印(df)”。使用正确范围的 for 循环,您是指 for 循环 1 还是 2?
  • 我的意思是请提供用于从网络中提取数据的所有代码。
  • Test = requests.get('reuters.com/finance/stocks/financial-highlights/'+i) ReutSoup = BeautifulSoup(Test.content,'html.parser')

标签: python web-scraping beautifulsoup


【解决方案1】:

Stack() 数据帧中的函数将列堆叠到第 1 层的行。

import requests
from bs4 import BeautifulSoup
import pandas as pd

LTGRMean = []
tickers = ['MMM', 'AES', 'LLY', 'LOW', 'PWR', 'TSCO', 'YUM', 'ICE', 'FB', 'AAPL', 'AMCR', 'FLS', 'GOOGL', 'FB', 'MSFT']

for i in tickers:
    Test = requests.get('https://www.reuters.com/finance/stocks/financial-highlights/' + i)
    ReutSoup = BeautifulSoup(Test.content, 'html.parser')
    td = ReutSoup.find('td', string="LT Growth Rate (%)")
    my_dict = {}
    #validate td object not none
    if td is not None:
        result = td.findNext('td').findNext('td').text
    else:
        result = "NaN"
    my_dict[i] = result
    LTGRMean.append(my_dict)

df = pd.DataFrame(LTGRMean)
print(df.stack())

O/P:

0   MMM       3.70
1   AES       9.00
2   LLY      10.42
3   LOW      13.97
4   PWR      12.53
5   TSCO     11.44
6   YUM      15.08
7   ICE       8.52
8   FB       19.90
9   AAPL     12.00
10  AMCR       NaN
11  FLS      19.04
12  GOOGL    16.14
13  FB       19.90
14  MSFT     14.80
dtype: object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多