python基於urllib與http訪問關鍵詞網站

urllib。request是http.client的抽象,要訪問網站,可以使用urllib.request.urlopen(),只需要一行代碼.

實驗原理

用urlencode()對於搜索的關鍵字進行url編碼,然後拼接到百度的網址後,應用urlopen()發出請求並取得結果,最後通過將結果進行解碼和正則搜索與字符串處理後輸出。

實驗效果

在這裏插入圖片描述

實驗代碼

from urllib.request import urlopen
from urllib.parse import urlencode
import re

## wd = input('輸入一個要搜索的關鍵字:')
wd = 'python'
wd = urlencode({'wd':wd})
url = 'http://www.baidu.com/s?' + wd
page = urlopen(url).read()
content = (page.decode('utf-8')).replace('\n','').replace('\t','')
title = re.findall(r'<h3 class="t".*?h3>',content)
title = [item[item.find('href = ') + 6:item.find('target=')] for item in title]
title = [item.replace(' ','').replace('"','') for item in title]
for item in title:
    print(item)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章