Python获取基金网站网页内容、使用BeautifulSoup库分析html操作示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python获取基金网站网页内容、使用BeautifulSoup库分析html操作示例

  2021-04-03 我要评论

本文实例讲述了Python获取基金网站网页内容、使用BeautifulSoup库分析html操作。分享给大家供大家参考,具体如下:

利用 urllib包 获取网页内容

#引入包
from urllib.request import urlopen
response = urlopen("http://fund.eastmoney.com/fund.html")
html = response.read();
#这个网页编码是gb2312
#print(html.decode("gb2312"))
#把html内容保存到一个文件
with open("1.txt","wb") as f:
  f.write(html.decode("gb2312").encode("utf8"))
  f.close()

使用BeautifulSoup分析html

from bs4 import BeautifulSoup
# 读取文件内容
with open("1.txt", "rb") as f:
  html = f.read().decode("utf8")
  f.close()
# 分析html内容
soup = BeautifulSoup(html,"html.parser")
# 取出网页title
print(soup.title) #<title>每日开放式基金净值表 _ 天天基金网</title>
# 基金编码
codes = soup.find("table",id="oTable").tbody.find_all("td","bzdm")
result = () # 初始化一个元组
for code in codes:
  result += ({
    "code":code.get_text(),
    "name":code.next_sibling.find("a").get_text(),
    "NAV":code.next_sibling.next_sibling.get_text(),
    "ACCNAV":code.next_sibling.next_sibling.next_sibling.get_text()
   },)
# 打印结果
print(result[0]["name"])

希望本文所述对大家Python程序设计有所帮助。

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们