用Python在新浪抓取TXT怎么抓,http://hi.baidu.com/nivrrex/blog/item/c662564e9a125a0eb3de05e3.html

用Python在新浪抓取TXT怎么抓,http://hi.baidu.com/nivrrex/blog/item/c662564e9a125a0eb3de05e3.html

有以下几个问题:1、地址变了,'http://book.sina.com.cn/nzt/novel/lit/wxdfd/index.shtml'会自动跳转成http://vip.book.sina.com.cn/book/index_46651.html。前者不含有目录内容,应替换地址2、提出目录块时,目录是ul列表里面有很多地址,但是现在的ul列表属于类变了。代码中用

    ,实际中是
      。根据比较,其他图书也改为现在的css类名字。3、提取出目录块后,相应的下载位置也要改变。u = 'http://book.sina.com.cn' + link[0]应改为u = ‘http://vip.book.sina.com.cn/book/' + link[0][1:-1]。后者会吧引号包含所以要去掉4、提取内容时,以前是根据“正文内容开始”和“正文内容结束”。现在我按的是正文的div,
      ================================变更以上=========================修改后的代码完整如下:# -*- coding: cp936 -*-import reimport urllibdef extract_links(html): blocks = re.findall(r'
        .*?', html, re.S) links = [] for b in blocks: links += re.findall(r']*>([^<>]*)', b) return linksdef extract_content(html): m = re.search('
        .*

        ', html, re.S) return m and html_to_text(m.group()) or ''def html_to_text(html): html = re.sub(r'

        (.*?)

        ', r'\1\n', html) html = re.sub(r'<[^<>]*>', '', html) return "\n\n" + html.strip() + "\n\n"def url_get(url): u = urllib.urlopen(url) c = u.read() u.close() return cdef download_book(urlindex, filename): links = extract_links(url_get(urlindex)) fp = open(filename, 'w') for link in links: u = 'http://vip.book.sina.com.cn/book/' + link[0][1:-1] title = link[1] fp.write(title) fp.write(extract_content(url_get(u))) print u print title fp.close()# 使用例子,下载并合成一个单独的 txtdownload_book('http://vip.book.sina.com.cn/book/index_46651.html', '五星大饭店.txt')