234213 发表于 2016-3-4 08:45:57

python小demo之自动向你推荐京东优惠电子书籍信息

这个小demo主要是用来向您推荐京东每天的限时优惠的电子书,链接:http://sale.jd.com/act/yufbrhZtjx6JTV.html。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#coding=utf-8
__author__ = 'kysida'
#导入库
import htmllib
import urllib2
import formatter
import string
import os

#定义类
class GetLinks(htmllib.HTMLParser):
    #初始化
    def __init__(self):
      #设置字典格式:links{href:link}
      self.links = {}
      #将传输过来的数据不做处理,格式化为数据流
      f = formatter.NullFormatter()
      htmllib.HTMLParser.__init__(self, f)

    #开始处理标签
    def anchor_bgn(self, href, name, type):
      self.save_bgn()
      self.link = href
    #结束处理标签
    def anchor_end(self):
      #去掉a标签保留a标签n内容
      text = string.strip(self.save_end())
      if self.link and text:
            self.links = self.link
#主程序
if __name__ == '__main__':
    #删除原有的文件
    try:
      os.remove('bookmenu.txt')
    except WindowsError:
      pass
    fp = urllib2.urlopen("http://sale.jd.com/act/yufbrhZtjx6JTV.html")
    data = fp.read()
    fp.close()
    #实例化
    demo = GetLinks()
    demo.feed(data)
    demo.close()

    for href, link in demo.links.items():
      #匹配link以‘http://e.jd.com/’开头的链接
      link_result = link.startswith('http://e.jd.com/')
      #href_result = href.startswith('立即下载')
      #去掉干扰的href
      if link_result == True and href != '立即下载':
            #print 'ok'
            #写入文件
            htmlfile = open('bookmenu.txt','a+')
            htmlfile.write("《"+href+"》"+'-------------->'+link + '\n\n')
            htmlfile.close()
      else:
            continue
    if True:
      print 'The book had been send successfully! '



页: [1]
查看完整版本: python小demo之自动向你推荐京东优惠电子书籍信息