- Yahoo、Sina 财经的API
- Python的Tushare包
- 自己手工爬取
Tushare是一个免费、开源的Python财经数据接口包,它对数据进行了规整因此使用起来非常方便。尽管有如此优秀的数据包简化了数据的采集工作,我们依然需要掌握从网站上爬取数据的技能,以获取接口没有提供的数据。本篇文章将会介绍一个小爬虫,告诉大家如何从网站上获取所有股票的代码和名称。
Python的urllib2库是爬虫的基础,使用urllib2库可以获取网页的内容,再使用正则表达式对所需的内容进行提取。我们在东方财富网的stocklist页面下对股票的代码和名字进行爬取,若要获取该网页下的全部内容,则需要以下几步:
- 对服务器发送一个请求,使用urllib2的Request方法返回reguest对象
- 采用urlopen方法处理构建的request对象,返回服务器的应答(response对象)
- 对response对象使用read方法,返回网页的内容
- request = urllib2.Request('http://quote.eastmoney.com/stocklist.html')
- response = urllib2.urlopen(request)
- content = response.read().decode("gbk")
一些网站不允许程序直接采用上面的方式进行访问,因此需要通过程序模拟浏览器的行为。通常采用的技术是在Requset方法的headers参数中设置agent,这样服务器认为是浏览器发出的请求就可以正常respose。
- url ='http://quote.eastmoney.com/stocklist.html'
- headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' }
- request = urllib2.Request(url,headers)
- try: urllib2.urlopen(request)except urllib2.URLError, e: if hasattr(e,"code"): print u"爬取股票列表失败,错误原因",e.reason
![view-source_quote_eastmoney_com_stocklist_html.jpg view-source_quote_eastmoney_com_stocklist_html.jpg](https://bbs-cdn.datacourse.cn/static/image/common/none.gif)
上图中蓝色标出的部分是我们需要的股票名称和代码,采取以下正则表达式可以获取需要的内容。正则表达式的写法不是唯一的,但需要保证使用该正则不会出现遗漏或多匹配出不需要的其他信息的情况。如果你对正则表达式不太熟悉也没有关系,Python提供了Beautiful Soup工具能够更为简单地提起Html或者Xml中的内容。
- pattern = re.compile('<li><a.*?href=.*?html">(.*?)\((.*?)\).*?</li>',re.S)
- items = re.findall(pattern,content)
- reload(sys)
- sys.setdefaultencoding('utf-8')
- f = open('stocklist.txt','w')
- for item in items:
- f.write(item[1]+','+item[0]+'\n')
- f.close()
- conn = sqlite3.connect("stock.db")
- cursor = conn.cursor()
- cursor.execute('''drop table if exists stock_index''')
- cursor.execute('''create table if not exists stock_index (stock_name varchar(60), id varchar(20))''')
- cursor.executemany("insert into stock_index(stock_name,id) values(?, ?)", stockList)
- conn.commit()
- cursor.close()
- conn.close()
我的微信公众号:会掘金的小鹿(NuggetsRoad)
是时候关注一波了!!