安装pip - Python的安装包管理工具 mac 已经自带Python,我的mac 系统是Sierra, 自带python版本是Python 2.7.13
sudo easy_install pip
相关工具安装: 1、网络请求工具 pip install lxml pip install requests
2、网页数据解析工具 pip install beautifulsoup4
3、解析器 pip install html5lib
示例1:获取我的简书首页展示的所有文章标题 ( http://www.jianshu.com/u/5b771dd604fd )
网页元素查看如下:
Python代码展示:
from lxml import htmlfrom lxml import etreefrom urllib import urlopenimport requestsimport bs4from bs4 import BeautifulSoupimport html5lib//网页数据获取examplePage = urlopen('http://www.jianshu.com/u/5b771dd604fd')//HTML数据soupExam = BeautifulSoup(examplePage,"html5lib")//网页标题print soupExam.titleprint soupExam.title.string//文章标题for link in soupExam.find_all('a',class_ = 'title'): print(link.text)复制代码
结果输出如下:
示例2:个别网站出现如下问题 1、希望获取红色标记中的数据:
2、但是获取到的都是 <\a> text </a> 中的text内容:
问题原因如下: (1)后台脚本requests网络数据,需要账号相关数据,解决方法为添加cookies; (2)网页有刷新机制,首先获取到的数据为刷新状态,解决方法为sleep一段时间;