1. 程式人生 > >爬取網頁中的連結

爬取網頁中的連結

獲取網頁內容

1、引入庫
import urllib
import urllib.request
2、獲取網頁內的所有資料
data = urllib.request.urlopen(“http://www.baidu.com").read()
3、將資料轉換成UTF-8編碼
data = data.decode(‘UTF-8’)
4、檢視網頁上獲取的資料
print(data)

對網頁內容進行篩選

1、引入庫
import re
2、正則表示式設定匹配內容
linkre = re.compile('href=\"(.+?)\"')
3、遍歷所有的匹配項

    for x in linkre.findall(data):
    	if 'http' in x
    		print('新增網址--->  ' + x)

4、檢視顯示結果
這就是網址頁面程式碼裡的所有href連結

將爬取的內容儲存至文字檔案

1、開啟檔案物件

file = open('檔案路徑','w')

2、將檔案內容逐行寫入檔案

for x in linkre.findall(data):
	if 'http' in x:
		file.write(x + '\n)