python爬蟲 ----文章爬蟲(合理處理字串中的\n\t\r........)

來源:互聯網
上載者:User

標籤:replace   src   去掉   page   ffffff   img   gb2312   back   range   

import urllib.requestimport reimport timenum=input("輸入日期(20150101000):")def openpage(url):    html=urllib.request.urlopen(url)        page=html.read().decode(‘gb2312‘)        return pagedef getpassage(page):    passage = re.findall(r‘<p class="MsoNormal" align="left">([\s\S]*)</FONT>‘,str(page))        passage1=re.sub("</?\w+[^>]*>", "", str(passage))        passage2=passage1.replace(‘\\r‘, ‘\r‘).replace(‘\\n‘, ‘ \n‘).replace(‘\\t‘,‘\t‘).replace(‘]‘,‘‘).replace(‘[‘,‘‘).replace(‘&nbsp;‘,‘   ‘)    print(passage2)    with open(load,‘a‘,encoding=‘utf-8‘) as f:        f.write("-----------------------------"+"日期"+str(date)+"---------------------------------\n"+passage2+"----------------------------------------------------\n")for i in range(1,32):    date=int(num)+int(i)    print(date)    load="C:/Users/home/Desktop/建立文字文件.txt"    url=("http://www.hbuas.edu.cn/news/xyxw/news_"+str(date)+".htm")    
  
try: page=openpage(url) getpassage(page) print("第"+str(i)+"號有文章,----已下載") except: print("第"+str(i)+"號無文章。") time.sleep(2)

 

寫了一個爬學校新聞網的爬蟲,

主要涉及   re正則   urllib.request   檔案的寫入  

在爬取文章時通常會返回很多影響美感的代碼

 如下:

 

 最佳化:

兩次正則    

passage = re.findall(r‘<p align="left">([\s\S]*)</FONT>‘,str(page))       #第一次匹配欄位    passage1=re.sub("</?\w+[^>]*>", "", str(passage))              # 第二次去掉html標籤

替換

passage2=passage1.replace(‘\\r‘, ‘\r‘).replace(‘\\n‘, ‘ \n‘).replace(‘\\t‘,‘\t‘).replace(‘]‘,‘‘).replace(‘[‘,‘‘).replace(‘&nbsp;‘,‘   ‘)

效果如下:

 

over!

python爬蟲 ----文章爬蟲(合理處理字串中的\n\t\r........)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.