【问题标题】:final dataframe from web-scraping multiple pages来自网络抓取多个页面的最终数据框
【发布时间】:2021-05-20 19:32:12
【问题描述】:

我想创建一个 pandas 数据框,其中包括从多页网站抓取的所有满足条件的行(我设法做到了)。但最终结果是我得到了只有行的 pandas 数据框属于我在循环中声明的范围的最后一页。如果有人指出错误出在哪里,而不是所有页面的结果,只有我得到的最后一个,我将不胜感激。

import requests
import pandas
from bs4 import BeautifulSoup

headers= {'User-Agent': 'Mozilla/5.0'}


for num in range (1,3):
    url =' https://biznes.interia.pl/gieldy/notowania-gpw/profil-akcji-grn,wId,7380,tab,przebieg-sesji,pack,{}'.format(num)
     

    response = requests.get(url,headers=headers)
    content = response.content
    soup = BeautifulSoup(content,"html.parser")

    notow = soup.find_all('table',class_ = 'business-table-trading-table')
    #on a given page, select only the rows containing the word "Transakcja" 
    rows = notow[0].select('tr:has(td:contains("TRANSAKCJA"))')
     
    data = []
    
    for row in rows :
        cols = row.find_all('td')
         
        cols = [ele.text.strip() for ele in cols]
         
        cols = data.append([ele for ele in cols if ele] )
        
         
 #final dataframe which should have  contained  the result from  all scraped pages        
        
df = pandas.DataFrame(data,)      
                      
print(df)

【问题讨论】:

    标签: python pandas beautifulsoup


    【解决方案1】:

    将代码 data = [] 放在循环之外。

    提取到列表 data 中的项目现在在最后一次循环迭代中重新初始化为空列表,有效地擦除在前 2 次循环迭代中提取的所有项。

    一般来说,避免在循环内初始化变量,除非你只在循环内使用变量。

    【讨论】:

    • 感谢您的快速提示
    • 欢迎您!请记住避免在循环内初始化变量,除非您仅在循环内使用变量。我已编辑答案以包含此一般准则。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多