网络数据抓取

192 阅读1分钟

安装pip - Python的安装包管理工具 mac 已经自带Python,我的mac 系统是Sierra, 自带python版本是Python 2.7.13 sudo easy_install pip

相关工具安装: 1、网络请求工具 pip install lxml pip install requests

2、网页数据解析工具 BeautifulSoup官网文档 pip install beautifulsoup4

3、解析器 pip install html5lib

示例1:获取我的简书首页展示的所有文章标题 ( http://www.jianshu.com/u/5b771dd604fd )

网页元素查看如下:

网页元素查看

Python代码展示:

from lxml import html
from lxml import etree
from urllib import urlopen
import requests
import bs4
from bs4 import BeautifulSoup
import html5lib

//网页数据获取
examplePage = urlopen('http://www.jianshu.com/u/5b771dd604fd')
//HTML数据
soupExam = BeautifulSoup(examplePage,"html5lib")
//网页标题
print soupExam.title
print 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一段时间;