zoukankan      html  css  js  c++  java
  • python 入门实践之网页数据抓取

    这个不错。正好入门学习使用。

    1、其中用到 feedparser:
    技巧:使用 Universal Feed Parser 驾驭 RSS
    http://www.ibm.com/developerworks/cn/xml/x-tipufp.html
    请访问 feedparser.org,详细了解 Universal Feed Parser,其中还包括一些下载资料和文档。

    feedparser 实际下载地址:
    http://code.google.com/p/feedparser/downloads/list

    2、另外,需要将文件加上 utf-8 的 bom 头,需要用到 python 写入十六进制字符:
    http://linux.byexamples.com/archives/478/python-writing-binary-file/
    python 写入十六进制字符
    file.write("x5Fx9Dx3E")
    file.close()

    3、因为要调试,文件的打开模式改成 w 方便一些。

    Python代码  收藏代码
      1. import urllib  
      2. import sys  
      3. import re  
      4. from feedparser import _getCharacterEncoding as enc  
      5.   
      6. class TagParser:  
      7.     def __init__(self, value):  
      8.         self.value = value  
      9.     def get(self, start, end):  
      10.         regx = re.compile(r'<' + start + r'.*?>.*</' + end + r'>')  
      11.         return re.findall(regx, self.value)  
      12.   
      13. if __name__ == "__main__":  
      14.     baseurl = "http://data.book.163.com/book/section/000BAfLU/000BAfLU"  
      15.     f = open("test_01.txt", "w")  
      16.     f.write("xefxbbxbf")  
      17. #    for ndx in range(0, 56):  
      18.     for ndx in range(0, 1):  
      19.         url = baseurl + str(ndx) + ".html"  
      20.         print "get content from " + url  
      21.         src = urllib.urlopen(url)  
      22.         text = src.read()  
      23.   
      24.     f1= open("tmp_" + str(ndx) + ".txt", "w")  
      25.     f1.write(text)  
      26.     f1.close()  
      27.   
      28.         encoding = enc(src.headers, text)[0]  
      29.      
      30.         tp = TagParser(text)  
      31.      
      32.         title = tp.get('h1 class="f26s tC"', 'h1')  
      33.         article = tp.get('p class="ti2em"', 'p')  
      34.      
      35.         t = re.sub(r'</.+>', ' ', title[0])  
      36.         t = re.sub(r'<.+>', ' ', t)  
      37.         data = t  
      38.      
      39.         c = ""  
      40.         for p in article:  
      41.             pt = re.sub(r'</p>', ' ', p)  
      42.             c += pt  
      43.         c = re.sub(r'<.+>', ' ', c)  
      44.         data += c  
      45.         data = data.decode(encoding)  
      46.         f.write(data.encode('utf-8', 'ignore'))  
      47.      
      48.     f.close()  
  • 相关阅读:
    P6665 [清华集训2016] Alice 和 Bob 又在玩游戏
    模板库
    CSP-S2021 游记
    CSP-S2021 SD迷惑行为大赏
    博弈论总结
    LOJ6033「雅礼集训 2017 Day2」棋盘游戏(二分图最大匹配必经点)
    LOJ6065「2017 山东一轮集训 Day3」第一题
    LOJ6059「2017 山东一轮集训 Day1」Sum
    LOJ6102「2017 山东二轮集训 Day1」第三题
    python笔记:字符编码
  • 原文地址:https://www.cnblogs.com/rrxc/p/4027974.html
Copyright © 2011-2022 走看看