使用簡單的python語句編寫爬蟲 定時拿取資訊並存入txt

來源:互聯網
上載者:User

標籤:網站   pil   目標   url   utf-8   編寫   for   att   ati   

# -*- coding: utf-8 -*-    #解決編碼問題
import urllib
import urllib2
import re
import os
import time

page = 1
url = ‘http://www.qiushibaike.com/text/page/4/?s=4970196‘ #爬取的目標網站
user_agent = ‘Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)‘
headers = { ‘User-Agent‘ : user_agent }
try:
request = urllib2.Request(url,headers = headers)
response = urllib2.urlopen(request)
# print response.read()
content = response.read().decode(‘utf-8‘) #解決編碼問題
pattern = re.compile(r‘<div.*?class="content".*?<span>(.*?)</span>.*?</div>‘,re.S) #第一個參數是匹配要爬取的內容,這裡使用正則去匹配
items = re.findall(pattern,content)
f=open(r‘.\article.txt‘,‘ab‘) #txt檔案路徑
nowTimes = time.strftime(‘%Y-%m-%d %H:%M:%S‘,time.localtime(time.time())) #擷取目前時間
f.write(‘時間:{}\n\n‘.format(nowTimes),); #txt檔案中寫入時間
for i in items:
i.encode(‘utf-8‘)
agent_info = u‘‘.join(i).encode(‘utf-8‘).strip()
f.writelines(‘段子:%s%s\n‘%(str(agent_info),os.linesep)) #分行存入
# f.write(‘%s‘%str(agent_info))
f.close()

# print items

except urllib2.URLError, e:
if hasattr(e,"code"):
print e.code
if hasattr(e,"reason"):
print e.reason


布置定時任務使用crontab。 (具體crontab使用方法可見http://blog.csdn.net/daivon_up/article/details/71266814):

使用簡單的python語句編寫爬蟲 定時拿取資訊並存入txt

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.