安裝pip - Python的安裝包管理工具
mac 已經(jīng)自帶Python,我的mac 系統(tǒng)是Sierra, 自帶python版本是Python 2.7.13
sudo easy_install pip
相關(guān)工具安裝:
1、網(wǎng)絡(luò)請求工具
pip install lxml pip install requests
2禁偎、網(wǎng)頁數(shù)據(jù)解析工具 BeautifulSoup官網(wǎng)文檔
pip install beautifulsoup4
3、解析器
pip install html5lib
示例1:獲取我的簡書首頁展示的所有文章標(biāo)題
( http://www.reibang.com/u/5b771dd604fd )
網(wǎng)頁元素查看如下:
Python代碼展示:
from lxml import html
from lxml import etree
from urllib import urlopen
import requests
import bs4
from bs4 import BeautifulSoup
import html5lib
//網(wǎng)頁數(shù)據(jù)獲取
examplePage = urlopen('http://www.reibang.com/u/5b771dd604fd')
//HTML數(shù)據(jù)
soupExam = BeautifulSoup(examplePage,"html5lib")
//網(wǎng)頁標(biāo)題
print soupExam.title
print soupExam.title.string
//文章標(biāo)題
for link in soupExam.find_all('a',class_ = 'title'):
print(link.text)
結(jié)果輸出如下:
示例2:個(gè)別網(wǎng)站出現(xiàn)如下問題
1如暖、希望獲取紅色標(biāo)記中的數(shù)據(jù):
2、但是獲取到的都是 <\a> text </a> 中的text內(nèi)容:
問題原因如下:
(1)后臺腳本requests網(wǎng)絡(luò)數(shù)據(jù)忌堂,需要賬號相關(guān)數(shù)據(jù)盒至,解決方法為添加cookies;
(2)網(wǎng)頁有刷新機(jī)制士修,首先獲取到的數(shù)據(jù)為刷新狀態(tài)枷遂,解決方法為sleep一段時(shí)間;