python3.4学习笔记(十四) 网络爬虫实例代码,抓取新浪爱彩双色球开奖数据实例

python3.4学习笔记(十四) 网络爬虫实例代码,抓取新浪爱彩双色球开奖数据实例

新浪爱彩双色球开奖数据URL:http://zst.aicai.com/ssq/openInfo/

最终输出结果格式如:2015075期开奖号码:6,11,13,19,21,32, 蓝球:4

直接用python源码写的抓取双色球最新开奖数据的代码,没使用框架,直接用字符串截取的方式写的,经过测试速度还是很快的

使用pyspider可以轻松分析出需要的内容,不过需要部署框架对只抓取特定内容的小应用来说也没多大必要
一般的抓取网页的使用 beautifulsoup就足够了,pyspider真正做爬虫类的应用才需要用到

python3.4学习笔记(十七) 网络爬虫使用Beautifulsoup4抓取内容 - 流风,飘然的风 - 博客园
http://www.cnblogs.com/zdz8207/p/python_learn_note_17.html

使用BeautifulSoup4对比直接使用字符串查找截取的方式要更加直观和简洁。

把代码作为开源项目了,热血狂徒 / zyspider - 代码托管 - 开源中国社区
http://git.oschina.net/coos/zyspider

====================================

 1 import urllib.request
 2 import urllib.parse
 3 import re
 4 import urllib.request,urllib.parse,http.cookiejar
 5 
 6 def getHtml(url):
 7     cj=http.cookiejar.CookieJar()
 8     opener=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
 9     opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36'),('Cookie','4564564564564564565646540')]
10 
11     urllib.request.install_opener(opener)
12     
13     html_bytes = urllib.request.urlopen( url ).read()
14     html_string = html_bytes.decode( 'utf-8' )
15     return html_string
16 
17 #url = http://zst.aicai.com/ssq/openInfo/
18 #最终输出结果格式如:2015075期开奖号码:6,11,13,19,21,32, 蓝球:4
19 html = getHtml("http://zst.aicai.com/ssq/openInfo/")
20 #<table class="fzTab nbt"> </table>
21 
22 table = html[html.find('<table class="fzTab nbt">') : html.find('</table>')]
23 #print (table)
24 #<tr onmouseout="this.style.background=''" onmouseover="this.style.background='#fff7d8'">
25 #<tr 
		                  onmouseout=
26 tmp = table.split('<tr 
		                  onmouseout=',1)
27 #print(tmp)
28 #print(len(tmp))
29 trs = tmp[1]
30 tr = trs[: trs.find('</tr>')]
31 #print(tr)
32 number = tr.split('<td   >')[1].split('</td>')[0]
33 print(number + '期开奖号码:',end='')
34 redtmp = tr.split('<td  class="redColor sz12" >')
35 reds = redtmp[1:len(redtmp)-1]#去掉第一个和最后一个没用的元素
36 #print(reds)
37 for redstr in reds:
38     print(redstr.split('</td>')[0] + ",",end='')
39 print('蓝球:',end='')
40 blue = tr.split('<td  class="blueColor sz12" >')[1].split('</td>')[0]
41 print(blue)