Python《十》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()
     },)
for item in result:
    print(item["name"]+"---"+item["NAV"])
# 打印结果
print(result[0]["name"])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值