1. 程式人生 > 實用技巧 >【Python學習日記】B站小甲魚:爬蟲

【Python學習日記】B站小甲魚:爬蟲

Web Spider

Python 如何訪問網際網路

URL + lib -->urllib

  URL的一般格式為 protocol://hostname[:port] / /path /[;parameters][?query]#fragment,其中[]為可選項

  URL由三部分組成

    第一部分是協議

    第二部分是存放資源的伺服器的域名系統或IP地址(有時候要包含埠號,各種傳輸協議都有預設的埠號)

    第三部分是資源的具體地址,如目錄或檔名

urllib是python的一個包

  下面這個程式展示了獲取百度新聞頁面的網頁資料的程式

import urllib.request

response 
= urllib.request.urlopen('http://news.baidu.com/') html = response.read() html = html.decode('utf-8') print(html)

  獲得的response是二進位制的,所以需要通過utf-8解碼


練習   從placekitten上儲存一張貓貓的圖片

import urllib.request

response = urllib.request.urlopen('http://placekitten.com/g/500/600')
cat_img = response.read()
with open('cat_500_600.jpg
','wb') as f: f.write(cat_img)

  首先urlopen的引數 可以是一個字串 也可以是一個request 物件

  因此程式碼也可以寫作把Request例項化

import urllib.request

req = urllib.request.Request('http://placekitten.com/g/500/600')
response = urllib.request.urlopen(req)

cat_img = response.read()
with open('cat_500_600.jpg', 'wb') as f:
    f.write(cat_img)

  Python提交POST表單訪問有道翻譯

  爬有道詞典,但是沒有成功,原因是有道翻譯添加了反爬機制salt和sign。

import urllib.request
import urllib.parse

url1 = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
data = {'i': '你好!', 'type': 'AUTO', 'doctype': 'json', 'version': '2.1', 'keyfrom': 'fanyi.web', 'ue': 'UTF-8',
        'typoresult': 'true'}
data = urllib.parse.urlencode(data).encode('utf-8')  # 把data編碼

response = urllib.request.urlopen(url1, data)  # 發出請求,得到相應
html = response.read().decode('utf-8')      #read之後得到的是utf-8的格式,解碼成Unicode的形式
print(html)


Request 有一個heads的引數,heads的格式是字典

修改heads可以通過兩個方式修改

  1.通過Request的headers引數修改

  2.通過Request.add_header()方法修改

為了使爬蟲更像人類,可以通過

1.time來控制時間戳,限制單位時間內IP的訪問次數

  import time

  ...

  time.sleep(5)

2.代理

  通過代理去訪問伺服器

  1.引數是一個字典{‘型別’ : ‘代理ip:埠號’}

    proxy_support = urllib.request.ProxyHandler({})

  2.定製一個opener

    opener = urllib.request.build_opener(proxy_support)

  3.1.安裝opener

    urllib.request.install_opener(opener)

  3.2.呼叫opener

    opener.open(url)

教程使用的網站現在都設定了複雜的反爬機制了,所以執行沒有成功。

import urllib.request

url = 'http://www.whatismyip.com.tw'
proxy_support = urllib.request.ProxyHandler({'http': '221.122.91.66:80'})

opener = urllib.request.build_opener(proxy_support)
opener.addheaders = {'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                                   'Chrome/84.0.4147.105 Safari/537.36'}

urllib.request.install_opener(opener)

response = urllib.request.urlopen(url)

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

print(html)