iOS 项目 --IM 即时通讯 (环信 SDK)

1,635 阅读1分钟
原文链接: www.jianshu.com
  • 读取网页代码
    import urllib.request
    import re
    indexUrl="http://www.shicimingju.com/book/sanguoyanyi.html"
    html =urllib.request.urlopen(indexUrl).read()
    html=html.decode('utf8')
  • 爬取书名book_name,爬取每章的名字chapter,爬取书的链接bookurl
    (具体问题具体分析,我这里在爬取每章的链接的时候发现竟然是相对路径,无法直接使用,于是只能针对书的链接进行字符串修改,从而来跳转到每章的页面。)
    book_name=re.findall('

    (.*)

    ',html,re.S) chapter=re.findall('href="/book/.{0,30}\d\.html">(.*?)',html,re.S) bookurl=re.findall('href="(/book/.{0,30}\d\.html)">',html,re.S) chapterUrlBegin=re.sub('.html','',indexUrl)#将书的链接替换成每章的链接开头
  • 爬取每章的内容chapterText,并且输出成文件。
    其中要注意看具体的输出,替换其中的一些字符和标签。
    for i in range(0,len(bookurl)):
      #提取每章的number
      number=re.findall('/(.{1,4})\.html',bookurl[i])
      #合并字符串形成每章的链接
      chapterUrl=re.sub('$',"/"+number[0]+".html",chapterUrlBegin)
      #打开链接网页
      chapterHtml=urllib.request.urlopen(chapterUrl).read()
      chapterHtml=chapterHtml.decode('utf-8','ignore')
      #找到每章内容
      chapterText=re.findall('
    (.*?)
    ',chapterHtml,re.S) #替换其中的标签

    和  chapterText=re.sub('

    ','',''.join(chapterText)) chapterText = re.sub('

    ', '', ''.join(chapterText)) chapterText = re.sub('', ' ', ''.join(chapterText)) #输出文件 f=open('D://book/'+"".join(book_name)+'.txt','a',encoding='utf-8') f.write(chapter[i]+"\n") f.write(chapterText+"\n") f.close()