与雪球网交互抓取股票数据

这些天写了一个简单的与雪球网交互的小程序,功能是运行后可以获取实时的股票价格,还有股票的历史价格,并将历史价格绘制成走势图。
python在爬虫方面有urllib、requests、BeautifulSoup4等工具库。urllib可用于抓取静态页面的html文本,requests可用于向网页发送请求(get/post)并获取返回的响应,BeautifulSoup库可用于对html页面的解析。

#设置matplotlib中文字体
font = FontProperties(fname=r"c:\\windows\\fonts\\simsun.ttc", size=14) 
#伪装浏览器登录
headers={
    "User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
}
#可以写一个url管理器来对url列表进行操作,此处先行指定几个
url=["https://xueqiu.com/S/NVDA","https://xueqiu.com/S/AMD","https://xueqiu.com/S/TSLA","https://xueqiu.com/S/BABA","https://xueqiu.com/S/AAPL"]
#抓取现在股票价格
def get_price(url):
    response=urllib.request.Request(url,headers=headers)
    html=urllib.request.urlopen(response).read().decode("utf-8")
    soup=BeautifulSoup(html,"html.parser")
    name=soup.find("div",class_="stock-name").get_text()
    price=soup.find("div",class_="stock-current").get_text()
    print(name+"现在的股价是:"+price)

查看更多