搜索引擎制作-如何制作搜索引擎,自己制作一个简单的搜索引擎呢?
【搜索引擎制作】如何制作搜索引擎,自己制作一个简单的搜索引擎呢?
我们能不能利用爬虫,自己制作一个简单的搜索引擎呢?
Why not?!我们自作简单的搜索引擎,展示输入词条的简介部分,这样可以既减少工作量,又展示了该搜索引擎的基本原理。
以下为笔者制作的简单的搜索引擎,实现的功能为:读取输入的词条,并输出百度百科里该词条的简介部分。
#
-*- coding: utf-8 -*-
"""
Created on Fri Aug 18 15:58:13 2017
@author:
JClian
"""
import re
import bs4
import urllib.request
from bs4
import BeautifulSoup
import urllib.parse
import sys
search_item
= input("Enter what you want(Enter 'out' to exit):")
while search_item !=
'out':
if search_item == 'out':
exit(0)
print("please
wait...")
try:
url =
'https://baike.baidu.com/item/'+urllib.parse.quote(search_item)
html
= urllib.request.urlopen(url)
content =
html.read().decode('utf-8')
html.close()
soup =
BeautifulSoup(content, "lxml")
text = soup.find('div',
class_="lemma-summary").children
print("search result:")
for x in text:
word =
re.sub(re.compile(r"<(.+?)>"),'',str(x))
words =
re.sub(re.compile(r"\[(.+?)\]"),'',word)
print(words,'\n')
except AttributeError:
print("Failed!Please enter more in
details!")
search_item = input("Enter what you want(Enter 'out' to
exit):")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
其中search_item为输入词条,进入while循环可一直搜索,当输入为’out’时退出。text为该词条的百度百科简介的网页形式,通过正则表达式将其中的文字提取出来(当然提取后的文字形式还有待美化~~)。如果百度百科里没有该词条,输出失败信息,并提示测试这将词条具体化些再输入。这样,百度百科有的词条,我们这个搜索引擎里也就有了响应的简介部分。
接下来是测试时间(在Jupyter Notebook上测试):
测试效果还是不错的,真是简单又好使,要不你也来试试?
卖贝商城更多商品介绍:万盛高端网站建设公司 咨询投资网站制作 大兴响应式网站建设