当前位置:   article > 正文

使用python获取网页数据并导出为json_提前 div 中数据 python

提前 div 中数据 python

使用beautifulSoup,并导出为json,做个记录。

  1. import requests
  2. from bs4 import BeautifulSoup
  3. import json
  4. # 定义目标URL
  5. url_pre = "https://www.baidu.com"
  6. url_suf = "/xx1/x.phtml"
  7. years = ["1","2","3","4","5"]
  8. # 初始化数据存储字典
  9. data_dict = {}
  10. for year in years:
  11.     # 发起GET请求获取页面内容
  12.     response = requests.get(url_pre+year+url_suf)
  13.     html_content = response.text
  14.     # 使用BeautifulSoup解析HTML内容
  15.     soup = BeautifulSoup(html_content, 'html.parser')
  16.     # 找到数据表格所在的标签
  17.     table = soup.find('table', id='id1')
  18.     # 遍历表格中的每一行
  19.     all_tr = table.find_all('tr')
  20.     #
  21.     shouRu = all_tr[3]
  22.     column_sr = shouRu.find_all('td')
  23.     if len(column_sr) >= 2:
  24.         key_sr = 'sr'
  25.         value1 = column_sr[1].text.strip().replace(',', '')
  26.         value2 = column_sr[2].text.strip().replace(',', '')
  27.         value3 = column_sr[3].text.strip().replace(',', '')
  28.         value4 = column_sr[4].text.strip().replace(',', '')
  29.         data_dict[year+key_sr+'1'] = value1
  30.         data_dict[year+key_sr+'2'] = value2
  31.         data_dict[year+key_sr+'3'] = value3
  32.         data_dict[year+key_sr+'4'] = value4
  33.     #
  34.     chengBen = all_tr[5]
  35.     column_cb = chengBen.find_all('td')
  36.     if len(column_cb) >= 2:
  37.         key_cb = 'cb'
  38.         value1 = column_cb[1].text.strip().replace(',', '')
  39.         value2 = column_cb[2].text.strip().replace(',', '')
  40.         value3 = column_cb[3].text.strip().replace(',', '')
  41.         value4 = column_cb[4].text.strip().replace(',', '')
  42.         data_dict[year+key_cb+'1'] = value1
  43.         data_dict[year+key_cb+'2'] = value2
  44.         data_dict[year+key_cb+'3'] = value3
  45.         data_dict[year+key_cb+'4'] = value4
  46.     #
  47.     liRun = all_tr[18]
  48.     column_lr = liRun.find_all('td')
  49.     if len(column_lr) >= 2:
  50.         key_lr = 'lr'
  51.         value1 = column_lr[1].text.strip().replace(',', '')
  52.         value2 = column_lr[2].text.strip().replace(',', '')
  53.         value3 = column_lr[3].text.strip().replace(',', '')
  54.         value4 = column_lr[4].text.strip().replace(',', '')
  55.         data_dict[year+key_lr+'1'] = value1
  56.         data_dict[year+key_lr+'2'] = value2
  57.         data_dict[year+key_lr+'3'] = value3
  58.         data_dict[year+key_lr+'4'] = value4
  59. # 将数据存储字典保存为JSON文件
  60. output_filename = "data.json"
  61. with open(output_filename, 'w') as json_file:
  62.     json.dump(data_dict, json_file, ensure_ascii=False, indent=4)
  63. print(f"数据已保存到{output_filename}")

对数据进行处理。

  1. import json
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. # 将JSON数据解析为字典
  5. with open('data.json', 'r', encoding='utf-8') as json_file:
  6. data_dict = json.load(json_file)
  7. # 初始化数据存储字典
  8. data = {
  9. "year": [],
  10. "zongshouru": [],
  11. "zongchengben": []
  12. }
  13. # 解析JSON数据并填充数据存储字典
  14. for year in ["1", "2", "3", "4", "5"]:
  15. sr_sum = sum(float(data_dict[f"{year}sr{i}"]) for i in range(1, 5))
  16. cb_sum = sum(float(data_dict[f"{year}cb{i}"]) for i in range(1, 5))
  17. data["year"].append(year)
  18. data["zongshouru"].append(sr_sum)
  19. data["zongchengben"].append(cb_sum)
  20. # 将数据存储字典转换为DataFrame
  21. df = pd.DataFrame(data)
  22. # 绘制折柱混合图
  23. plt.figure(figsize=(10, 6))
  24. # 绘制折线图
  25. plt.plot(df["year"], df["zsr"], marker='o', label="zsr", color="blue")
  26. plt.plot(df["year"], df["zcb"], marker='o', label="zcb", color="orange")
  27. # 绘制柱状图
  28. plt.bar(df["year"], df["zsr"], width=0.4, align='center', alpha=0.5, color="blue")
  29. plt.bar(df["year"], df["zcb"], width=0.4, align='edge', alpha=0.5, color="orange")
  30. plt.xlabel('year')
  31. plt.ylabel('amount')
  32. plt.title('this is title(unit: 100K)')
  33. plt.legend()
  34. plt.grid(True)
  35. plt.show()

对数据进行处理的部分2,进行折线图绘制使用echart

  1. # 根据季报数据,计算出公司近五年(20182022年)的营业利润,
  2. # 分年度展示每一年四个季度的营业利润。
  3. # 要求:年度可以切换,使用折线图展示
  4. import json
  5. import pandas as pd
  6. import matplotlib.pyplot as plt
  7. # 将JSON数据解析为字典
  8. with open('data.json', 'r', encoding='utf-8') as json_file:
  9. data_dict = json.load(json_file)
  10. # 初始化数据存储字典
  11. data = {
  12. "年份": [],
  13. "Q1": [],
  14. "Q2": [],
  15. "Q3": [],
  16. "Q4": []
  17. }
  18. # 解析JSON数据并填充数据存储字典
  19. for year in ["1", "2", "3", "4", "5"]:
  20. data["年份"].append(year)
  21. for quarter in ["Q1", "Q2", "Q3", "Q4"]:
  22. lr_key = f"{year}lr{quarter[1]}"
  23. if lr_key in data_dict:
  24. data[quarter].append(float(data_dict[lr_key]))
  25. else:
  26. data[quarter].append(0.0)
  27. # print(data)
  28. # 将数据存储字典转换为DataFrame
  29. df = pd.DataFrame(data)
  30. # 绘制折线图
  31. plt.figure(figsize=(10, 6))
  32. for quarter in ["Q1", "Q2", "Q3", "Q4"]:
  33. plt.plot(df["年份"], df[quarter], marker='o', label=quarter)
  34. plt.xlabel('year')
  35. plt.ylabel('lirun')
  36. plt.title('Company 5 years Every Quarters LiRun')
  37. plt.legend()
  38. plt.grid(True)
  39. plt.show()

 记录一下python的学习过程。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/963321
推荐阅读
相关标签
  

闽ICP备14008679号