一、环境准备
1、python3版本
C:\Users\king>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
二、爬取天天基金网某只基金的当天的净值估算

1、代码
import urllib.request
from bs4 import BeautifulSoup
fund_code = '002851'
url = 'http://fund.eastmoney.com/{}.html?spm=search'.format(fund_code)
page = urllib.request.urlopen(url)
# 获得了整个网页的内容也就是源代码
contents = page.read().decode("utf-8")
# 用来获取web元素
soup = BeautifulSoup(contents, "html.parser")
# 获取span标签下id为gz_gsz的内容
today_nav = soup.find('span', id='gz_gsz').get_text()
print('today_nav = ', today_nav)
效果:
today_nav = 1.4903
2、需要避免的坑
①python 3.x中urllib库和urilib2库合并成了urllib库,所以安装urilib2会失败;
②把urllib2.urlopen() 改成 urllib.request.urlopen()
③python 3.x中request被作为一个模块而不是方法
④python 3.x使用from bs4 import BeautifulSoup,python 2.x使用from bs3 import BeautifulSoup直接导入bs4包即可
⑤编码记得utf-8
三、赠语
不经一番寒彻骨,怎得梅花扑鼻香。
网友评论