生活随笔
收集整理的這篇文章主要介紹了
python(数据分析与可视化)二
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
python(數(shù)據(jù)分析與可視化)二
爬取網(wǎng)頁內(nèi)容的前期技術(shù)儲備
1.pip包管理
(1)內(nèi)置庫
包/庫:別人寫好的代碼,直接引用,加快開發(fā)效率。
內(nèi)置包:python解釋器內(nèi)置常用功能庫。
– 解釋器安裝目錄/Lib文件夾下, os time urllib等
– 文件夾里有__init__.py 就成了一個包。
...
import urllib
from urllib
import request
response
= request
.urlopen('http://baidu.com')
...
(2)關(guān)于HTTP模擬和HTML源代碼解析
python時代: urllib urllib2
由第三方程序員做了一個新http請求庫,比官方更方便,urllib3
又有一個程序員,在urllib3基礎(chǔ)上進(jìn)一步封裝和優(yōu)化,requests
python3時代 內(nèi)置庫統(tǒng)一為urllib
結(jié)論:建議直接使用requests
(3)第三方庫
pypi.org 上豐富的各種功能的庫
①pip包管理工具
在服務(wù)器上沒有圖形界面的瀏覽器.開發(fā)語言第三方庫往往用命令行包管理工具
解釋器/script/pip.exe
pip
-V # 看Pip版本
pip search requests #搜索包信息
pip install requests #安裝第三方庫
pip uninstall requests #卸載
pip list #展示所有已經(jīng)安裝過的庫
pip freeze
> requirements
.txt #把項目用到的庫信息導(dǎo)出到一個文件中
第三方庫安裝的位置: 解釋器目錄\lib\site-packages\
②換源
軟件源source: 清單里維護(hù)了上萬的 某某軟件-> 某某url下載 庫下載地址關(guān)系,但官方pypi.org下載速度慢,國內(nèi)一些大學(xué)、大公司同步鏡像
方法一:臨時換源
‘pip install requests -i http://simply.aliyun.com/simply/’
方法二:永久換
系統(tǒng)用戶文件夾下新建.pip文件夾和pip.conf文件,寫入配置
方式三(推薦):pycharm設(shè)置里面配settings/interpreter/+號/manage repositories/+號 復(fù)制源(推薦阿里云)
參考[pip換源](https://www.cnblogs.com/believepd/p/10499844.html)
豆瓣 https://pypi.doubanio.com/simple/
阿里云 https://mirrors.aliyun.com/pypi/simple/
清華大學(xué) https://pypi.tuna.tsinghua.edu.cn/simple/
2.requests基本用法
requests 是用Python語言編寫,基于 urllib,采用 Apache2 Licensed 開源協(xié)議的 HTTP 庫。它比 urllib 更加方便,可以節(jié)約我們大量的工作,完全滿足 HTTP 測試需求。Requests 的哲學(xué)是以 PEP 20 的習(xí)語為中心開發(fā)的,所以它比 urllib 更加 Pythoner。下面我以代碼的形式簡單寫其中常用的幾個知識點:
import requestsbaidu_index_url
= 'https://baidu.com'
baidu_search_url
= 'http://baidu.com/s'#仿造請求頭,基本反爬蟲措施
headers
= {#
'cookies':'', #跟公共參數(shù)、用戶會話有關(guān)#
'refer':'', #從哪個頁面來#瀏覽器標(biāo)識,容易偽造,但肯定是機(jī)器人,容易被服務(wù)器識別出來
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'
}params
= {'wd':'天氣','ie':'utf-8'
}response
= requests
.get(url
=baidu_search_url
,params
=params
)
#狀態(tài)碼
status_code
= response
.status_code
if status_code
== 200:#網(wǎng)頁數(shù)據(jù) bytescontent
= response
.content#網(wǎng)頁數(shù)據(jù)str 一般直接取得text屬性,但少數(shù)情況解碼錯誤出現(xiàn)亂碼text
= response
.texttext
= content
.decode('utf-8') #只有百度需要()特殊
print(text
)url
= response
.urlheaders
= response
.headers
3.debug模式
debug模式也就是調(diào)試運行模式
具體操作過程可以分為三步:
1.打斷點
2.以debug運行
3.F8向下執(zhí)行單步,觀察變量值
import requestsresponse
= requests
.get(url
='https://baidu.com', )
# 狀態(tài)碼
status_code
= response
.status_code
if status_code
== 200:# 網(wǎng)頁數(shù)據(jù) bytescontent
= response
.content# 網(wǎng)頁數(shù)據(jù)str 一般直接取得text屬性,但少數(shù)情況解碼錯誤出現(xiàn)亂碼text
= response
.texttext
= content
.decode('utf-8')print(text
)url
= response
.urlheaders
= response
.headers
for i
in range(10):print(i
)j
= ij
+=1print(1)
4.html解析—正則
①我們已經(jīng)用requests模擬請求,拿到網(wǎng)頁源代碼,str字符串,里面HTML模式
#需要分析
字符串自帶的find方法功能有限,如下:
html
= '<html><body><h1>標(biāo)題</h1></body></html>'
start_index
= html
.find('<h1>')
end_index
= html
.find('</h1>')
print(html
[start_index
:end_index
])
因此有三種解析方法:
解析方式一:正則 regex,專門針對字符串處理的語法
(不推薦,了解即可)
import re
text1
= 'ilikepythonbutyouarebeautiful'
pattern1
= re
.compile(r
'python')
matcher1
= re
.search(pattern1
,text1
)
print(matcher1
[0])text2
= '<h1>i like world</h1>'
pattern2
= re
.compile(r
'<h1>.+</h1>') #
. 表示一個字符
matcher2
= re
.search(pattern2
,text2
)
print(matcher2
[0])text3
= 'beautiful'
text4
= 'you are a good boy'
text5
= '13243454454@qq.com'
#注冊驗證郵箱#手冊 https
://tool
.oschina
.net
/uploads
/apidocs
/jquery
/regexp
.html
#常用正則 https
://www
.cnblogs
.com
/qq364735538
/p
/11099572.htmltext6
= """
<html
>
aaacc
<h1
>adsd
sss
</h1
>
aaaa
</html
>
"""
pattern10
= re
.compile(r
'<h1>(.*?)</h1>',re
.S)
print(pattern10
.findall(text6
))#把網(wǎng)頁上
HTML目標(biāo)區(qū)域標(biāo)簽復(fù)制到上述代碼中,像抓取的信息用(.*?)代替
5.html解析—bs庫(不推薦,了解即可)
#網(wǎng)頁HTML本身就是樹狀層狀結(jié)構(gòu),按照層次去找
#beautiful-soup庫 是python2時代的庫,
#適合python3的是beautifulsoup4
#用’pip install beautifulsoup4‘來安裝第三方庫
from bs4
import BeautifulSoup #小坑:代碼包名和包原信息名字不一致html
= """
<html
><body
><a id
='xxx' href
="https://baidu.com">百度一下
</a
><a
></a
></body
>
</html
>
"""#先把字符串解析成html結(jié)構(gòu),內(nèi)置庫html
.parser 或者第三方庫lxml
bs
= BeautifulSoup(html
,'html.parser') #或者第二個參數(shù)填入“l(fā)xml”
print(bs
.a
)
print(bs
.find_all('a'))
print(bs
.a
['href'])
print(bs
.a
)
#獲取父、子標(biāo)簽#總結(jié):bs邏輯直觀簡單,但代碼較多
6.html解析—xpath
#xpath表達(dá)式有自己的語法,但沒有正則那么復(fù)雜,類似bs4庫按照html層級查找
#用’pip install lxml‘來進(jìn)行第三方庫的安裝
from lxml
import etreehtml
= """
<!DOCTYPE html
>
<html lang
="en">
<head
><meta charset
="UTF-8" /><title
>lxml中xpath的用法
</title
>
</head
>
<body
><ul
><li
><a href
="https://www.baidu.com" class="first_a">百度一下
</a
></li
><li
><a href
="https://mail.qq.com" id
="second_a">QQ郵箱
</a
></li
><li
><a href
="https://www.taobao.com">淘寶網(wǎng)
</a
></li
><li
><a href
="https://pypi.python.org" class="first_a">Python官網(wǎng)
</a
><a href
="https://pypi.python.org" class="second_a">Python
</a
></li
></ul
><p
class="one">first_p_tag
</p
><p id
="second">second_p_tag
</p
><div
class="one">first_div_tag
<p
class="first second third">11111111</p
><a href
="#">22222222</a
></div
>
</body
>
</html
>
"""#把長字符串轉(zhuǎn)換成html文檔樹
dom
= etree
.HTML(html
)
print(dom
)#默認(rèn)情況下都是全文匹配,匹配不到返回空列表
,匹配到的【element
,element】
#
"/"表示往下一層 “
dom
.xpath('//a')
#取html元素里的屬性
#
"/@href"取元素屬性值
dom
.xpath('//a/@href')
#取標(biāo)簽里面的內(nèi)容
-> "/text()"
print(dom
.xpath('//a/text()'))
# 屬性過濾
print(dom
.xpath('//a[@id="second_a"]/text()')[0])
比較正則xpathbs
| 難度 | 難 | 中 | 簡單 |
| 代碼量 | 少 | 少 | 多 |
| 可讀性 | | 好 | |
今天的分享就到這里,如果還想了解更多,可以看我主頁!
總結(jié)
以上是生活随笔為你收集整理的python(数据分析与可视化)二的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。