日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python网络爬虫基础知识_Python网络爬虫基础知识

發布時間:2024/10/12 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python网络爬虫基础知识_Python网络爬虫基础知识 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、網絡爬蟲

網絡爬蟲又被稱為網絡蜘蛛,我們可以把互聯網想象成一個蜘蛛網,每一個網站都是一個節點,我們可以使用一只蜘蛛去各個網頁抓取我們想要 的資源。舉一個最簡單的例子,你在百度和谷歌中輸入‘Python',會有大量和Python相關的網頁被檢索出來,百度和谷歌是如何從海量的網頁中檢索 出你想要的資源,他們靠的就是派出大量蜘蛛去網頁上爬取,檢索關鍵字,建立索引數據庫,經過復雜的排序算法,結果按照搜索關鍵字相關度的高低展現給你。

千里之行,始于足下,我們從最基礎的開始學習如何寫一個網絡爬蟲,實現語言使用Python。

二、Python如何訪問互聯網

想要寫網絡爬蟲,第一步是訪問互聯網,Python如何訪問互聯網呢?

在Python中,我們使用urllib包訪問互聯網。 (在Python3中,對這個模塊做了比較大的調整,以前有urllib 和urllib2,在3中對這兩個模塊做了統一合并,稱為urllib包。包下面包含了四個模 塊,urllib.request,urllib.error,urllib.parse,urllib.robotparser) ,目前主要使用的是urllib.request。

我們首先舉一個最簡單的例子,如何獲取獲取網頁的源碼:

importurllib.request

response= urllib.request.urlopen('https://docs.python.org/3/')

html=response.read()print(html.decode('utf-8'))

三、Python網絡簡單使用

首先我們用兩個小demo練一下手,一個是使用python代碼下載一張圖片到本地,另一個是調用百度翻譯寫一個翻譯小軟件。

3.1根據圖片鏈接下載圖片,代碼如下:

importurllib.request

response= urllib.request.urlopen('http://www.3lian.com/e/ViewImg/index.html?url=http://img16.3lian.com/gif2016/w1/3/d/61.jpg')

image=response.read()

with open('123.jpg','wb') as f:

f.write(image)

其中response是一個對象

輸入: response.geturl()

->'http://www.3lian.com/e/ViewImg/index.html?url=http://img16.3lian.com/gif2016/w1/3/d/61.jpg'

輸入:

response.info()

->

輸入: print(response.info())

->Content-Type: text/html

Last-Modified: Mon, 27 Sep 2004 01:23:20 GMT

Accept-Ranges: bytes

ETag: "0f4b59230a4c41:0"

Server: Microsoft-IIS/8.0

Date: Sun, 14 Aug 2016 07:16:01 GMT

Connection: close

Content-Length: 2827

輸入: response.getcode()

->200

3.1使用有道詞典實現翻譯功能

我們想實現翻譯功能,我們需要拿到請求鏈接。首先我們需要進入有道首頁,點擊翻譯,在翻譯界面輸入要翻譯的內容,點擊翻譯按鈕,就會向服務器發起一個請求,我們需要做的就是拿到請求地址和請求參數。

我在此使用谷歌瀏覽器實現拿到請求地址和請求參數。首先點擊右鍵,點擊檢查 (不同瀏覽器點擊的選項可能不同,同一瀏覽器的不同版本也可能不同) ,進入圖一所示,從中我們可以拿到請求請求地址和請求參數,在Header中的Form Data中我們可以拿到請求參數。

(圖一)

代碼段如下:

importurllib.requestimporturllib.parse

url= 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=dict2.index'data={}

data['type'] = 'AUTO'data['i'] = 'i love you'data['doctype'] = 'json'data['xmlVersion'] = '1.8'data['keyfrom'] = 'fanyi.web'data['ue'] = 'UTF-8'data['action'] = 'FY_BY_CLICKBUTTON'data['typoResult'] = 'true'data= urllib.parse.urlencode(data).encode('utf-8')

response=urllib.request.urlopen(url,data)

html= response.read().decode('utf-8')print(html)

上述代碼執行如下:

{"type":"EN2ZH_CN","errorCode":0,"elapsedTime":0,"translateResult":[[{"src":"i love you","tgt":"我愛你"}]],"smartResult":{"type":1,"entries":["","我愛你。"]}}

對于上述結果,我們可以看到是一個json串,我們可以對此解析一下,并且對代碼進行完善一下:

importurllib.requestimporturllib.parseimportjson

url= 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=dict2.index'data={}

data['type'] = 'AUTO'data['i'] = 'i love you'data['doctype'] = 'json'data['xmlVersion'] = '1.8'data['keyfrom'] = 'fanyi.web'data['ue'] = 'UTF-8'data['action'] = 'FY_BY_CLICKBUTTON'data['typoResult'] = 'true'data= urllib.parse.urlencode(data).encode('utf-8')

response=urllib.request.urlopen(url,data)

html= response.read().decode('utf-8')

target=json.loads(html)print(target['translateResult'][0][0]['tgt'])

四、規避風險

服務器檢測出請求不是來自瀏覽器,可能會屏蔽掉請求,服務器判斷的依據是使用‘User-Agent',我們可以修改改字段的值,來隱藏自己。代碼如下:

importurllib.requestimporturllib.parseimportjson

url= 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=dict2.index'data={}

data['type'] = 'AUTO'data['i'] = 'i love you'data['doctype'] = 'json'data['xmlVersion'] = '1.8'data['keyfrom'] = 'fanyi.web'data['ue'] = 'UTF-8'data['action'] = 'FY_BY_CLICKBUTTON'data['typoResult'] = 'true'data= urllib.parse.urlencode(data).encode('utf-8')

req=urllib.request.Request(url, data)

req.add_header('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36')

response=urllib.request.urlopen(url, data)

html= response.read().decode('utf-8')

target=json.loads(html)print(target['translateResult'][0][0]['tgt'])

View Code

上述做法雖然可以隱藏自己,但是還有很大問題,例如一個網絡爬蟲下載圖片軟件,在短時間內大量下載圖片,服務器可以可以根據IP訪問次數判斷是否 是正常訪問。所有上述做法還有很大的問題。我們可以通過兩種做法解決辦法,一是使用延遲,例如5秒內訪問一次。另一種辦法是使用代理。

延遲訪問(休眠5秒,缺點是訪問效率低下):

importurllib.requestimporturllib.parseimportjsonimporttimewhileTrue:

content= input('please input content(input q exit program):')if content == 'q':break;

url= 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=dict2.index'data={}

data['type'] = 'AUTO'data['i'] =content

data['doctype'] = 'json'data['xmlVersion'] = '1.8'data['keyfrom'] = 'fanyi.web'data['ue'] = 'UTF-8'data['action'] = 'FY_BY_CLICKBUTTON'data['typoResult'] = 'true'data= urllib.parse.urlencode(data).encode('utf-8')

req=urllib.request.Request(url, data)

req.add_header('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36')

response=urllib.request.urlopen(url, data)

html= response.read().decode('utf-8')

target=json.loads(html)print(target['translateResult'][0][0]['tgt'])

time.sleep(5)

View Code

代理訪問:讓代理訪問資源,然后講訪問到的資源返回。服務器看到的是代理的IP地址,不是自己地址,服務器就沒有辦法對你做限制。

步驟:

1,參數是一個字典{'類型' : '代理IP:端口號' } //類型是http,https等

proxy_support = urllib.request.ProxyHandler({})

2,定制、創建一個opener

opener = urllib.request.build_opener(proxy_support)

3,安裝opener(永久安裝,一勞永逸)

urllib.request.install_opener(opener)

3,調用opener(調用的時候使用)

opener.open(url)

五、批量下載網絡圖片

圖片下載來源為煎蛋網(http://jandan.net)

圖片下載的關鍵是找到圖片的規律,如找到當前頁,每一頁的圖片鏈接,然后使用循環下載圖片。下面是程序代碼(待優化):

importurllib.requestimportosdefurl_open(url):

req=urllib.request.Request(url)

req.add_header('User-Agent','Mozilla/5.0')

response=urllib.request.urlopen(req)

html=response.read()returnhtmldefget_page(url):

html= url_open(url).decode('utf-8')

a= html.find('current-comment-page') + 23b= html.find(']',a)returnhtml[a:b]deffind_image(url):

html= url_open(url).decode('utf-8')

image_addrs=[]

a= html.find('img src=')while a != -1:

b= html.find('.jpg',a,a + 150)if b != -1:

image_addrs.append(html[a+9:b+4])else:

b= a + 9a= html.find('img src=',b)for each inimage_addrs:print(each)returnimage_addrsdefsave_image(folder,image_addrs):for each inimage_addrs:

filename= each.split('/')[-1]

with open(filename,'wb') as f:

img=url_open(each)

f.write(img)def download_girls(folder = 'girlimage',pages = 20):

os.mkdir(folder)

os.chdir(folder)

url= 'http://jandan.net/ooxx/'page_num=int(get_page(url))for i inrange(pages):

page_num-=i

page_url= url + 'page-' + str(page_num) + '#comments'image_addrs=find_image(page_url)

save_image(folder,image_addrs)if __name__ == '__main__':

download_girls()

總結

以上是生活随笔為你收集整理的python网络爬虫基础知识_Python网络爬虫基础知识的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。