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)


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