使用requests+beautifulsoup模块实现python网络爬虫功能
来源:互联网 发布:淘宝店如何上架宝贝 编辑:程序博客网 时间:2024/03/19 09:25
1. 前言
之前实现python的网络爬虫, 主要都是使用较为底层的urllib, urllib2 实现的, 这种实现方案显得比较原始, 编码起来也比较费劲, 尤其是提取信息的时候, 还得使用正则表达是匹配 (之前转载的一篇糗事百科的爬虫文章,http://blog.csdn.net/zhyh1435589631/article/details/51296734)。 我们这里采用requests + beautifulsoup 的实现方案, 使用 css 选择器, 简化代码的书写。
2. 基本资料
- 当然在使用这两个模块之前, 需要对这两个模块做一些介绍:
requests 主要是一个封装好了http功能的库, 可以实现基本的http操作
beautifulsoup 主要提供了对html, xml网页的一个完美的解析方式, 实际上, 他将html中的tag 作为树节点进行解析, 于是, 我们可以将一个html页面看成是一颗树结构。 - requests 官方文档: http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
- beautifulsoup 官方文档: https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
3. 实现代码
代码比较简洁, 就不多说了, 下面的代码中, 我们分别爬取两个网站, 糗事百科 和 我们学校的就业网站。
# -*- coding=utf8 -*-import requestsfrom bs4 import BeautifulSoupdef qiushibaike(): content = requests.get('http://www.qiushibaike.com').content soup = BeautifulSoup(content, 'html.parser') for div in soup.find_all('div', {'class' : 'content'}): print div.text.strip()def ustcjob(): headers = {'User-Agent':'Mozilla / 5.0(X11;Linux x86_64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 50.0.2661.102 Safari / 537.36'} content = requests.get('http://job.ustc.edu.cn/list.php?MenuID=002', headers = headers).content soup = BeautifulSoup(content, 'html.parser') for Jop in soup.find_all('div', {'class' : 'Joplistone'}): for item in Jop.find_all('li'): print "%-30s%-20s%-40s" % (item.a.text.strip() , item.span.text.strip() , item.span.next_sibling.text.strip())if __name__ == '__main__': #qiushibaike() ustcjob()
- 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
4. 实现效果
糗事百科
阅读全文
0 0
- 使用requests+beautifulsoup模块实现python网络爬虫功能
- 使用requests+beautifulsoup模块实现python网络爬虫功能
- python网络爬虫-使用BeautifulSoup
- python 爬虫试手 requests+BeautifulSoup
- Python下基于requests及BeautifulSoup构建网络爬虫
- Python爬虫实例——基于BeautifulSoup和requests实现
- Python 爬虫实战(一):使用 requests 和 BeautifulSoup
- 【Python爬虫】requests+Beautifulsoup存入数据库
- Python爬虫入门之一-requests+BeautifulSoup
- 【爬虫】Python的Requests模块
- python学习(6):python爬虫之requests和BeautifulSoup的使用
- Python-网络爬虫之BeautifulSoup
- 使用python语言结合beautifulsoup编写简单的网络爬虫
- python简单爬虫开发(urllib2、requests + BeautifulSoup)
- Python爬虫笔记之用BeautifulSoup及requests库爬取
- python股票数据爬虫requests、etree、BeautifulSoup学习
- Python使用BeautifulSoup进行爬虫
- python3实现网络爬虫(2)--BeautifulSoup使用(1)
- XGBoost-Python完全调参指南-参数解释篇
- Python学习笔记(6)- 列表的切片
- 1032. 挖掘机技术哪家强(20)——C语言
- jsp连接数据库
- .aar 编译 与 android studio 的bug
- 使用requests+beautifulsoup模块实现python网络爬虫功能
- SpringMVC处理Ajax02
- 2017.11.10笔记
- HP laserJet Pro MFP M126nw打印机连接无线设置
- java中如何给Runnable线程传递参数?
- Android 监听双卡信号强度
- quartz定时器入门示例
- Hystrix系列之熔断器
- C#实战小技巧(三):Semaphore信号量