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)