python爬蟲初探

2021-08-13 22:59:00 字數 2629 閱讀 4028

,確保程式引用類庫是否是引用的該目錄,否則會出現pip install chardet 後,無法在專案中呼叫chardet的問題.可能在會出現pip安裝到/usr/local/lib/python2.7/dist-packages下,但是程式在/usr/local/lib/python2.7/dist-packages下在引用,出現無法引用問題

官方位址

b.安裝[此為python2.7]

1. 解壓*.gz檔案放到python 類庫目錄  /usr/lib/python2.7/dist-packages  

2.使用pip  insall  chardet 

爬蟲**

#-*-coding:utf-8-*-

importurllib2

importchardetaschardet

importre

classdemo2:

defreaddata(self):

url_link =''#get pages

設定超時時間

#html = urllib2.urlopen(url_link,timeout=30).read()

source_html = urllib2.urlopen('').read()

#print html

mychar = chardet.detect(source_html)

encode = mychar['encoding']

ifencode =='utf-8'orencode =='utf-8':

source_data=source_html

elifencode =='gbk'orencode =='gbk':

#如與程式編碼格式

utf-8

不一致,

為gbk,

則使用utf-8

進行解碼後再編碼

source_data = source_html.decode('gbk','ignore').encode('utf-8')

elifencode =='gb2312'orencode =='gb2312':

source_data = source_html.decode('gb2312','ignore').encode('utf-8')

#print source_data

#print '\n',type(source_data)

#返回抓取的資料

returnsource_data

defmatchdata(self,sourcedata):

regex =r'.*'#

返回pattern

物件rules = re.compile(regex)

#for i in sourcedata#根據

patter

物件對字串進行匹配

result = rules.findall(source_data,0,len(source_data))

foriinresult:

regex2 =r'.*'rules2 = re.compile(regex2)

res = rules2.findall(i,0,len(i))

regex3 =r'>.*<'rules2 = re.compile(regex3)

res3 = rules2.findall(res)

printres3

returnresult

if__name__ =='__main__':

demo = demo2()

source_data = demo.readdata()

result = demo.matchdata(sourcedata=source_data)

#print result

Python爬蟲初探

閒來無事研究了一下python的爬蟲技術,現在總結一下 testclass.py 檔案 加上這個可以輸入中文 coding utf 8 匯入幾個內建庫 import urllib import urllib2 import re import mytool 模擬瀏覽器和請求頭,否則顯示訪問出錯 us...

Python爬蟲初探

以下功能均在jupyter notebook上實現。python及相應爬蟲工具安裝請參考部落格 一 爬蟲介紹 1.非結構化資料 沒有固定格式 如網頁資料,必須通過etl extract 抽取 transformation 轉換 loading 組成 工具將數 據轉化為結構化資料才能取用。raw da...

Python爬蟲 初探多執行緒爬蟲

上篇,我們已經建立了乙個基本的爬蟲,用來抓取動態網頁的資訊。經過測試,爬蟲的速度太慢,我們需要改進。這篇我會介紹如何實現乙個多執行緒的python爬蟲來提高抓取網頁的效率。很多人都說因為python的gil gil規定每個時刻只能有乙個執行緒訪問python虛擬機器 限制,不應該用多執行緒,而應該用...