一、環(huán)境準備
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.
>>>
二台盯、爬取天天基金網(wǎng)某只基金的當(dāng)天的凈值估算
圖1.png
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)
# 獲得了整個網(wǎng)頁的內(nèi)容也就是源代碼
contents = page.read().decode("utf-8")
# 用來獲取web元素
soup = BeautifulSoup(contents, "html.parser")
# 獲取span標簽下id為gz_gsz的內(nèi)容
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直接導(dǎo)入bs4包即可
⑤編碼記得utf-8
三、贈語
不經(jīng)一番寒徹骨蚣常,怎得梅花撲鼻香市咽。