初解Python爬蟲(一)

1、robots.txt

robots.txt(統一小寫)是一種存放於網站根目錄下的 ASCII 編碼的文本文件,它一般告訴網絡搜索引擎的漫遊器(又稱網絡蜘蛛),此網站中的哪些內容是不該被搜索引擎的漫遊器獲取的,哪些是能夠被漫遊器獲取的。由於一些系統中的 URL 是大小寫敏感的,因此 robots.txt 的文件名應統一爲小寫。robots.txt 應放置於網站的根目錄下。若是想單獨定義搜索引擎的漫遊器訪問子目錄時的行爲,那麼能夠將自定的設置合併到根目錄下的 robots.txt,或者使用 robots 元數據(Metadata,又稱元數據)。php

robots.txt 協議並非一個規範,而只是約定俗成的,因此並不能保證網站的隱私。注意 robots.txt 是用字符串比較來肯定是否獲取 URL,因此目錄末尾有與沒有斜槓 「/」 表示的是不一樣的URL。robots.txt 容許使用相似 "Disallow: *.gif" 這樣的通配符。css

其餘的影響搜索引擎的行爲的方法包括使用robots元數據:html

<meta name="robots" content="noindex,nofollow" />

這個協議也不是一個規範,而只是約定俗成的,有些搜索引擎會遵照這一規範,有些則否則。一般搜索引擎會識別這個元數據,不索引這個頁面,以及這個頁面的鏈出頁面。python

容許全部的機器人:nginx

User-agent: *
Disallow:

# 另外一寫法:
User-agent: *
Allow:/

僅容許特定的機器人:(name_spider用真實名字代替)git

User-agent: name_spider
Allow:

攔截全部的機器人:github

User-agent: *
Disallow: /

禁止全部機器人訪問特定目錄:json

User-agent: *
Disallow: /cgi-bin/
Disallow: /images/
Disallow: /tmp/
Disallow: /private/

僅禁止壞爬蟲訪問特定目錄(BadBot用真實的名字代替):api

User-agent: BadBot
Disallow: /private/

禁止全部機器人訪問特定文件類型[2]:跨域

User-agent: *
Disallow: /*.php$
Disallow: /*.js$
Disallow: /*.inc$
Disallow: /*.css$

通常咱們在查看robots文件時,是主域名後面添加如:http://www.xxx.xxx/robots.txt

2、requests

在開始使用 requests 以前,咱們須要確認兩點:

a. 使用的 Python 的版本是否已安裝 requests

pip install requests

b. requests 是否爲最新版本

如今咱們就能夠開始瞭解 requests 了。

2.1 發送請求

一開始要導入 Requests 模塊

import requests

而後,嘗試獲取某個網頁。本例子中,咱們來獲取 Github 的公共時間線

r = requests.get('https://api.github.com/events')

如今,咱們有一個名爲 r 的 Response 對象。咱們能夠從這個對象中獲取全部咱們想要的信息。

import requests
r = requests.get('https://api.github.com/events')
print(r)


''' 運行結果 : 返回的是請求狀態 200
<Response [200]>
'''

Requests 簡便的 API 意味着全部 HTTP 請求類型都是顯而易見的。例如,咱們能夠這樣發送一個 HTTP POST 請求,以及 PUT,DELETE,HEAD 以及 OPTIONS 

import requests

r = requests.get('https://api.github.com/events')
r1 = requests.post('http://httpbin.org/post', data = {'key':'value'})
r2 = requests.put('http://httpbin.org/put', data = {'key':'value'})
r3 = requests.delete('http://httpbin.org/delete')
r4 = requests.head('http://httpbin.org/get')
r5 = requests.options('http://httpbin.org/get')

2.2 傳遞 URL 參數

你也許常常想爲 URL 的查詢字符串 (query string) 傳遞某種數據。若是你是手工構建 URL,那麼數據會以鍵/值對的形式置於 URL 中,跟在一個問號的後面。例如, httpbin.org/get?key=val。 Requests 容許你使用 params 關鍵字參數,以一個字符串字典來提供這些參數。舉例來講,若是你想傳遞 key1=value1 和 key2=value2 到 httpbin.org/get ,那麼你可使用以下代碼:

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)

經過打印該 URL,咱們會發現參數已經被編碼進去

print(r.url)

''' 打印URL結果
http://httpbin.org/get?key1=value1&key2=value2
'''

這裏須要注意的是:字典裏值爲 None 的鍵都不會被添加到 URL 的查詢字符串裏。

列表也能夠做爲值傳入:

payload = {'key1': 'value1', 'key2': ['value2', 'value3']}

r = requests.get('http://httpbin.org/get', params=payload)
print(r.url)

''' 運行結果
http://httpbin.org/get?key1=value1&key2=value2&key2=value3
'''

2.3 響應內容

咱們能讀取服務器響應的內容。再次以 GitHub 時間線爲例

import requests
r = requests.get('https://api.github.com/events')
print(r.text)

正常狀況下,咱們會獲得一個一個 json 串,因格式化後有近3000行,咱們這裏只選取前面幾行的結果

[{
	"id": "7817414078",
	"type": "IssueCommentEvent",
	"actor": {
		"id": 17928298,
		"login": "jknpj",
		"display_login": "jknpj",
		"gravatar_id": "",
		"url": "https://api.github.com/users/jknpj",
		"avatar_url": "https://avatars.githubusercontent.com/u/17928298?"
	},
	"repo": {
		"id": 10441188,
		"name": "vgstation-coders/vgstation13",
		"url": "https://api.github.com/repos/vgstation-coders/vgstation13"
	},

Requests 會自動解碼來自服務器的內容。大多數 unicode 字符集都能被無縫地解碼。

請求發出後,Requests 會基於 HTTP 頭部對響應的編碼做出有根據的推測。當你訪問 r.text 之時,Requests 會使用其推測的文本編碼。你能夠找出 Requests 使用了什麼編碼,而且可以使用 r.encoding 屬性來改變它。

>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'

若是你改變了編碼,每當你訪問 r.text ,Request 都將會使用 r.encoding 的新值。你可能但願在使用特殊邏輯計算出文本的編碼的狀況下來修改編碼。好比 HTTP 和 XML 自身能夠指定編碼。這樣的話,你應該使用 r.content 來找到編碼,而後設置 r.encoding 爲相應的編碼。這樣就能使用正確的編碼解析 r.text 了。

在你須要的狀況下,Requests 也可使用定製的編碼。若是你建立了本身的編碼,並使用 codecs 模塊進行註冊,你就能夠輕鬆地使用這個解碼器名稱做爲 r.encoding 的值, 而後由 Requests 來爲你處理編碼。

2.4 二進制響應內容

也能以字節的方式訪問請求響應體,對於非文本請求:

>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...


Requests 會自動爲你解碼 gzip 和 deflate 傳輸編碼的響應數據。

例如,以請求返回的二進制數據建立一張圖片,你能夠如下面的形式實現

>>> from PIL import Image
>>> from io import BytesIO

>>> i = Image.open(BytesIO(r.content))

2.5 JSON 響應內容

Requests 中也有一個內置的 JSON 解碼器,助你處理 JSON 數據

>>> import requests

>>> r = requests.get('https://api.github.com/events')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

若是 JSON 解碼失敗, r.json() 就會拋出一個異常。例如,響應內容是 401 (Unauthorized),嘗試訪問 r.json() 將會拋出 ValueError: No JSON object could be decoded 異常。

這裏須要注意的是,成功調用 r.json() 並不意味着響應的成功。有的服務器會在失敗的響應中包含一個 JSON 對象(好比 HTTP 500 的錯誤細節)。這種 JSON 會被解碼返回。要檢查請求是否成功,請使用 r.raise_for_status() 或者檢查 r.status_code 是否和你的指望相同。

2.6 原始響應內容

在罕見的狀況下,你可能想獲取來自服務器的原始套接字響應,那麼你能夠訪問 r.raw。 若是你確實想這麼幹,那請你確保在初始請求中設置了 stream=True。具體你能夠這麼作:

>>> r = requests.get('https://api.github.com/events', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

但通常狀況下,你應該如下面的模式將文本流保存到文件:

with open(filename, 'wb') as fd:
    for chunk in r.iter_content(chunk_size):
        fd.write(chunk)

使用 Response.iter_content 將會處理大量你直接使用 Response.raw 不得不處理的。 當流下載時,上面是優先推薦的獲取內容方式。 Note that chunk_size can be freely adjusted to a number that may better fit your use cases.

2.7 定製請求頭

若是你想爲請求添加 HTTP 頭部,只要簡單地傳遞一個 dict 給 headers 參數就能夠了。

例如,在前一個示例中咱們沒有指定 content-type

>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}

>>> r = requests.get(url, headers=headers)

注意: 定製 header 的優先級低於某些特定的信息源,例如:

1)若是在 .netrc 中設置了用戶認證信息,使用 headers= 設置的受權就不會生效。而若是設置了 auth= 參數,``.netrc`` 的設置就無效了。
2) 若是被重定向到別的主機,受權 header 就會被刪除。
3) 代理受權 header 會被 URL 中提供的代理身份覆蓋掉。
4) 在咱們能判斷內容長度的狀況下,header 的 Content-Length 會被改寫。
更進一步講,Requests 不會基於定製 header 的具體狀況改變本身的行爲。只不過在最後的請求中,全部的 header 信息都會被傳遞進去。

注意: 全部的 header 值必須是 string、bytestring 或者 unicode。儘管傳遞 unicode header 也是容許的,但不建議這樣作。

2.8 POST一個多部分編碼(Multipart-Encoded)的文件

Requests 使得上傳多部分編碼文件變得很簡單

>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}

你能夠顯式地設置文件名,文件類型和請求頭

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}

若是你想,你也能夠發送做爲文件來接收的字符串

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "some,data,to,send\\nanother,row,to,send\\n"
  },
  ...
}

若是你發送一個很是大的文件做爲 multipart/form-data 請求,你可能但願將請求作成數據流。默認下 requests 不支持, 但有個第三方包 requests-toolbelt 是支持的。你能夠閱讀 toolbelt 文檔來了解使用方法。

2.9 響應狀態碼

咱們能夠檢測響應狀態碼

>>> r = requests.get('http://httpbin.org/get')
>>> r.status_code
200

爲方便引用,Requests 還附帶了一個內置的狀態碼查詢對象

>>> r.status_code == requests.codes.ok
True

若是發送了一個錯誤請求(一個 4XX 客戶端錯誤,或者 5XX 服務器錯誤響應),咱們能夠經過 Response.raise_for_status() 來拋出異常

>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r.status_code
404

>>> bad_r.raise_for_status()
Traceback (most recent call last):
  File "requests/models.py", line 832, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error

可是,因爲咱們的例子中 r 的 status_code 是 200 ,當咱們調用 raise_for_status() 時,獲得的是:

>>> r.raise_for_status()
None

3.0 響應頭

咱們能夠查看以一個 Python 字典形式展現的服務器響應頭:

>>> r.headers
{
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json'
}

可是這個字典比較特殊:它是僅爲 HTTP 頭部而生的。根據 RFC 2616, HTTP 頭部是大小寫不敏感的。

所以,咱們可使用任意大寫形式來訪問這些響應頭字段

>>> r.headers['Content-Type']
'application/json'

>>> r.headers.get('content-type')
'application/json'

它還有一個特殊點,那就是服務器能夠屢次接受同一 header,每次都使用不一樣的值。但 Requests 會將它們合併,這樣它們就能夠用一個映射來表示出來

A recipient MAY combine multiple header fields with the same field name into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field value to the combined field value in order, separated by a comma.

接收者能夠合併多個相同名稱的 header 欄位,把它們合爲一個 "field-name: field-value" 配對,將每一個後續的欄位值依次追加到合併的欄位值中,用逗號隔開便可,這樣作不會改變信息的語義。

3.1 Cookie

若是某個響應中包含一些 cookie,你能夠快速訪問它們

>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)

>>> r.cookies['example_cookie_name']
'example_cookie_value'

要想發送你的cookies到服務器,可使用 cookies 參數

>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')

>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

Cookie 的返回對象爲 RequestsCookieJar,它的行爲和字典相似,但接口更爲完整,適合跨域名跨路徑使用。你還能夠把 Cookie Jar 傳到 Requests 中:

>>> jar = requests.cookies.RequestsCookieJar()
>>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
>>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
>>> url = 'http://httpbin.org/cookies'
>>> r = requests.get(url, cookies=jar)
>>> r.text
'{"cookies": {"tasty_cookie": "yum"}}'

3.2 重定向與請求歷史

默認狀況下,除了 HEAD, Requests 會自動處理全部重定向。

可使用響應對象的 history 方法來追蹤重定向。

Response.history 是一個 Response 對象的列表,爲了完成請求而建立了這些對象。這個對象列表按照從最老到最近的請求進行排序。

例如,Github 將全部的 HTTP 請求重定向到 HTTPS

>>> r = requests.get('http://github.com')

>>> r.url
'https://github.com/'

>>> r.status_code
200

>>> r.history
[<Response [301]>]

若是你使用的是GET、OPTIONS、POST、PUT、PATCH 或者 DELETE,那麼你能夠經過 allow_redirects 參數禁用重定向處理:

>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]

若是你使用了 HEAD,你也能夠啓用重定向:

>>> r = requests.head('http://github.com', allow_redirects=True)
>>> r.url
'https://github.com/'
>>> r.history
[<Response [301]>]

3.3 超時

你能夠告訴 requests 在通過以 timeout 參數設定的秒數時間以後中止等待響應。基本上全部的生產代碼都應該使用這一參數。若是不使用,你的程序可能會永遠失去響應:

>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

注意:timeout 僅對鏈接過程有效,與響應體的下載無關。 timeout 並非整個下載響應的時間限制,而是若是服務器在 timeout 秒內沒有應答,將會引起一個異常(更精確地說,是在 timeout 秒內沒有從基礎套接字上接收到任何字節的數據時)If no timeout is specified explicitly, requests do not time out.

3.4 錯誤與異常

遇到網絡問題(如:DNS 查詢失敗、拒絕鏈接等)時,Requests 會拋出一個 ConnectionError 異常。

若是 HTTP 請求返回了不成功的狀態碼, Response.raise_for_status() 會拋出一個 HTTPError 異常。

若請求超時,則拋出一個 Timeout 異常。

若請求超過了設定的最大重定向次數,則會拋出一個 TooManyRedirects 異常。

全部Requests顯式拋出的異常都繼承自 requests.exceptions.RequestException 。

 

參考資料

1. 維基百科-robots.txt

2. http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

相關文章
相關標籤/搜索