python–小白入门练习

  • 2018-09-26
  • 118
  • 2

最近学了点python,所以就简单写个文章,分享下

demo

1: 爬去豆瓣前250数据

#!/usr/bin/python
# coding:utf-8

import requests
from bs4 import BeautifulSoup

test_url = 'http://movie.douban.com/top250/'

def download_page(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'
    }
    data = requests.get(url,headers=headers).content
    return data

movie_name_list = []
def parse_html(html):
    soup = BeautifulSoup(html)
    movie_list_soup = soup.find('ol', attrs={'class': 'grid_view'})
    if movie_list_soup != None:
        for movie_li in movie_list_soup.find_all('li'):
            detail = movie_li.find('div', attrs={'class': 'hd'})
            movie_name = detail.find('span', attrs={'class': 'title'}).getText()
            movie_name_list.append(movie_name)

        next_page = soup.find('span', attrs={'class': 'next'}).find('a')
        if next_page:
            parse_html(download_page(test_url + next_page['href']))
        return movie_name_list

def main():
    handle = parse_html(download_page(test_url))
    if handle != None:
        handle = list(handle)
        for ele in handle:
            print (ele)

if __name__ == '__main__':
    main()

2.实现一个事实监控股票数据的系统

import tushare as ts
import datetime
import time

class Stock():
  def __init__(self, q, stock_num='002736'):
    self.q=q
    self.stock_num=stock_num
    self._terminal=True

  def query_stock_real_price(self):
    df = ts.get_realtime_quotes(self.stock_num)
    df=df[['price','time']]
    price=df['price'].values[0]
    time=df['time'].values[0]
    print(df)
    return price,time

  def get_kline_data(self, ktype='ma5'):
    today=datetime.datetime.now().strftime('%Y-%m-%d')
    df = ts.get_hist_data(self.stock_num, start='2018-08-08', end=today)
    return (df[[ktype]])

  def start_run(self):
    while self._terminal:
      p,t=self.query_stock_real_price()
      print ('--->',t,p)
      # print (''.format(t, p))
      format(t, p)
      real_price=float(p)
      self.q = real_price
      time.sleep(3)

  def stop_run(self):
    self._terminal=False

s = Stock('a')
s.start_run()

这一部分是通过 tushare 这个包来获取股票的一些数据,还有通过邮件提醒功能。
附上git地址:https://github.com/YTU94/learn-python

学习网站

1.不错的微信公众号:菜鸟学Python

好文

1.入门够了:https://mp.weixin.qq.com/

源码地址: https://github.com/YTU94/learn-python

评论

- 友情链接 - Theme by Qzhai