Python爬虫 | 您所在的位置:网站首页 › 搜索引擎和网络爬虫 › Python爬虫 |
平时我们要搜索某个东西的时候,我们往往会用到百度百科,比如搜“上海”,会出现以下页面: 那么,我们能不能利用爬虫,自己制作一个简单的搜索引擎呢? 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):")其中search_item为输入词条,进入while循环可一直搜索,当输入为’out’时退出。text为该词条的百度百科简介的网页形式,通过正则表达式将其中的文字提取出来(当然提取后的文字形式还有待美化~~)。如果百度百科里没有该词条,输出失败信息,并提示测试这将词条具体化些再输入。这样,百度百科有的词条,我们这个搜索引擎里也就有了响应的简介部分。 接下来是测试时间(在Jupyter Notebook上测试): 测试效果还是不错的,真是简单又好使,要不你也来试试? 本篇分享如有不足之处,还请批评指正。欢迎交流^O^ 期待下一篇分享…注意:本人现已开通两个微信公众号: 因为Python(微信号为:python_math)以及轻松学会Python爬虫(微信号为:easy_web_scrape), 欢迎大家关注哦~~ |
CopyRight 2018-2019 实验室设备网 版权所有 |