1. 程式人生 > >python初學-爬取網頁資料

python初學-爬取網頁資料

python初學-爬取網頁資料

1,獲取網頁原始碼

import urllib
url = 'http://www.163.com'

wp = urllib.urlopen(url)
file_content = wp.read()

print file_content

2,將網頁內容存入檔案中

fp = open('163.txt', 'wb') #開啟一個文字檔案

fp.write(file_content) #寫入資料

fp.close() #關閉檔案

3,利用正則表示式快速的打印出網頁的標題跟連結地址

import re
fp = open('163.txt'
, 'rb') content = fp.read() fp.close() title = re.search('<title>(.*?)</title>', content, re.S).group(1) print 'title = ', title + '\n' hrefPatten = 'href="(.*?)"' hrefC = re.findall(hrefPatten, content, re.S) #返回所有匹配正則表示式的值於列表中 print 'Allhref = ', hrefC for h in hrefC : print h

只是示例程式碼,演示爬取簡單內容的簡單過程,程式不完善,謝謝閱讀,有不明白的可以回覆討論。