我想创建一个熊猫数据框,其中包含满足条件的所有行(我设法做到了),这些行是从一个多页网站中刮取的。但是最终结果是,我得到的熊猫数据框只包含属于该行的行我在循环中声明的范围的最后一页。如果有人指出错误出在哪里,而不是所有页面的结果,我将不胜感激。
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)
将代码data = []
放在循环之外。
现在,提取到列表data
中的项目将在上一次循环迭代中重新初始化为空列表,从而有效擦除在前两次循环迭代中提取的所有项目。
通常,除非您仅在循环内使用变量,否则避免在循环内初始化变量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句