python3.5简单爬虫爬取百度百科(参考imooc实战)
来源:互联网 发布:2017全国最新人口数据 编辑:程序博客网 时间:2024/05/20 01:47
思路:
1、添加一个入口url
2、解析该url对应的html中的内容,提取标签与内容,再从中提取其中所含的其他百科的链接,因此,维护新老两个set,防止重复url
3、由于一个页面解析出来的百科链接不止一个,所以要计数break
4、将内容保存在一个html文件中
#coding=gbk'''Created on 2016年6月23日@author: Administrator'''from bs4 import BeautifulSoupimport reimport urllib.parseimport urllib.requestnew_urls = set()old_urls = set()datas = []NewUrls = set()def crawler(root_url): tot = 1 count = 1 new_urls.add(root_url) while len(new_urls) != 0: try: new_url = new_urls.pop() old_urls.add(new_url) print('正在打印第 %d个: %s'%(tot,new_url)) if new_url is None: continue response = urllib.request.urlopen(new_url) if response.getcode() != 200: continue html_cont = response.read() soup = BeautifulSoup(html_cont, 'html.parser', from_encoding='utf-8') links = soup.find_all('a', href=re.compile(r"/view/\d+\.htm")) for link in links: new_urllrh = link['href'] new_full_url = urllib.parse.urljoin(new_url, new_urllrh) new_urls.add(new_full_url) new_data = {} new_data['url'] = new_url title_node = soup.find('dd', class_="lemmaWgt-lemmaTitle-title").find('h1') new_data['title'] = title_node.get_text() summary_node = soup.find('div', class_="lemma-summary") new_data['summary'] = summary_node.get_text() datas.append(new_data) if tot == 30: break tot = tot + 1 except: print('第%d次使用套路失败'%count) if count == 3: break count += 1 fout = open('output.html', 'w', encoding="utf-8") fout.write("<html>") fout.write("<head><meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\"></head>") fout.write("<body>") fout.write("<table>") for data in datas: fout.write("<tr>") fout.write("<td>%s</td>" % data['url']) fout.write("<td>%s</td>" % data['title']) fout.write("<td>%s</td>" % data['summary']) fout.write("</tr>") fout.write("</table>") fout.write("</body>") fout.write("</html>") fout.close() if __name__ == '__main__': root_url = "http://baike.baidu.com/view/21087.htm" crawler(root_url)
如有错误,欢迎提出
0 0
- python3.5简单爬虫爬取百度百科(参考imooc实战)
- python3.6.2实现的简单爬虫爬取百度百科
- Python3爬虫之四简单爬虫架构【爬取百度百科python词条网页】
- 简单的python爬虫(爬取百度百科词条)
- Python 简单爬虫实现(爬取百度百科信息)
- python3 爬虫学习-根据关键词爬取百度百科内容
- python3爬虫(1)--百度百科的页面爬取
- [python3]爬虫实战一之爬取糗事百科段子
- 实践项目十:爬取百度百科Python词条相关1000个页面数据(慕课简单爬虫实战)
- Python3 爬取百度百科
- 第一个python爬虫(python3爬取百度百科1000个页面)
- 简单爬虫——爬取百度百科总结
- 简单爬虫-爬取百度百科1000个页面
- 简单的爬虫----爬取百度百科练习
- python3爬虫(二)实战- 爬糗事百科
- Python简单爬虫开发的学习笔记整理(爬取百度百科词条)
- Python3 简单爬虫爬取百度贴吧帖子
- python3 [入门基础实战] 爬虫入门之爬取糗事百科
- RedisTemplate API
- REST服务开发实战
- 答疑java初学者常见问题
- JavaMaill:使用MIME协议创建内含图片的复杂邮件
- mysql常用基础操作语法(十)~~子查询【命令行模式】
- python3.5简单爬虫爬取百度百科(参考imooc实战)
- bootstrap modal弹出框的垂直居中
- PHP的魔术方法及异常
- JavaMail入门:创建纯文本、HTML格式的邮件
- AngularJS-MVC(1-1)
- 我写哒有关photoshop曲线工具的攻略,跟编程没啥关系就不发了发下我新浪博客的链接
- cvSetImageROI 感兴趣区域选择
- ubuntu14.04编译PTAM
- Android之ToolBar项目封装,踩坑过河