Python3爬蟲(2)_利用urllib.urlopen發送數據獲得反饋信息


一、urlopen的url參數 Agent

 url不僅可以是一個字符串,例如:https://baike.baidu.com/。url也可以是一個Request對象,這就需要我們先定義一個Request對象,然后將這個Request對象作為urlopen的參數使用,

代碼:

1 from urllib import request
2 
3 if __name__ == "__main__":
4     req = request.Request("https://baike.baidu.com//")
5     response = request.urlopen(req)
6     html = response.read()
7     html = html.decode("utf-8")
8     print(html)

運行之后,結果就不做展示了。

urlopen()返回的對象,可以使用read()進行讀取,同樣也可以使用geturl()方法、info()方法、getcode()方法。

  • geturl()返回的是一個url的字符串;

  • info()返回的是一些meta標記的元信息,包括一些服務器的信息;

  • getcode()返回的是HTTP的狀態碼,如果返回200表示請求成功。

下面更新代碼,進行下面的測試:

from urllib import request

if __name__=="__main__":
    re=request.Request("http://baike.baidu.com")
    response=request.urlopen(re)
    print("geturl打印信息:%s"%(response.geturl()))
    print('**********************************************')
    print("info打印信息:%s"%(response.info()))
    print('**********************************************')
    print("getcode打印信息:%s"%(response.getcode()))

二、urlopen的data參數

    我們可以使用data參數,向服務器發送數據。根據HTTP規范,GET用於信息獲取,POST是向服務器提交數據的一種請求,再換句話說:

    從客戶端向服務器提交數據使用POST;

    從服務器獲得數據到客戶端使用GET(GET也可以提交,暫不考慮)。

    如果沒有設置urlopen()函數的data參數,HTTP請求采用GET方式,也就是我們從服務器獲取信息,如果我們設置data參數,HTTP請求采用POST方式,也就是我們向服務器傳遞數據。

    data參數有自己的格式,它是一個基於application/x-www.form-urlencoded的格式,具體格式我們不用了解, 因為我們可以使用urllib.parse.urlencode()函數將字符串自動轉換成上面所說的格式。

三、發送data實例

遇到一些問題,我也暫時使用有道翻譯,以后有好的方法更新這部分關於百度百科的爬取。

向有道翻譯發送數據,得到網頁反饋:

1.打開界面

2.鼠標右鍵檢查元素

3.選擇網絡/network

4.在搜索輸入框 輸入查找內容,“network”界面出現了大量內容。

5.得到下方內容:

編寫新程序:

 

from urllib import request
from urllib import parse
import json

if __name__ == "__main__":
    Request_URL = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
    Form_Data = {}
    Form_Data['i'] = 'Web'
    Form_Data['from'] = 'AUTO'
    Form_Data['to'] = 'AUTO'
    Form_Data['smartresult'] = 'dict'
    Form_Data['client'] = 'fanyideskweb'
    Form_Data['salt'] = '1524700622507'
    Form_Data['sign'] = 'c8c86253bcfb23d8405ab58cc0d2b5fa'
    Form_Data['doctype'] = 'json'
    Form_Data['xmlVersion'] = '2.1'
    Form_Data['keyfrom'] = 'fanyi.web'
    Form_Data['action'] = 'FY_BY_CLICKBUTTON'
    data = parse.urlencode(Form_Data).encode('utf-8')
    response = request.urlopen(Request_URL,data)
    html = response.read().decode('utf-8')
    translate_results = json.loads(html)
    translate_results = translate_results['translateResult'][0][0]['tgt']
    print("翻譯的結果是:%s" % translate_results)

報錯:

RESTART: C:\Users\DELL\AppData\Local\Programs\Python\Python36\urllib_test01.py
Traceback (most recent call last):
File "C:\Users\DELL\AppData\Local\Programs\Python\Python36\urllib_test01.py", line 23, in <module>
translate_results = translate_results['translateResult'][0][0]['tgt']
KeyError: 'translateResult'

這是因為data['salt']是時間戳,data['sign']是時間戳和翻譯內容加密后生成的,因為不知道網站的加密方法,

在這里選擇調整uri和data,並根據http://bbs.fishc.com/thread-98973-1-1.html這里的帖子做出調整:

import os,urllib.request
import urllib.parse
import json
a = 5
while a > 0:
        txt = input('輸入要翻譯的內容:')
        if txt == '0':
                break
                
        else:
                url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&sessionFrom=https://www.baidu.com/link'
                data = {
                'from':'AUTO',
                'to':'AUTO',
                'smartresult':'dict',
                'client':'fanyideskweb',
                'salt':'1524700622507',
                'sign':'c8c86253bcfb23d8405ab58cc0d2b5fa',
                'doctype':'json',
                'version':'2.1',
                'keyfrom':'fanyi.web',
                'action':'FY_BY_CL1CKBUTTON',
                'typoResult':'false'}

                data['i'] = 'Web'

                data = urllib.parse.urlencode(data).encode('utf - 8')
                wy = urllib.request.urlopen(url,data)
                html = wy.read().decode('utf - 8')
                print(html)

                ta = json.loads(html)
                print('翻譯結果: %s '% (ta['translateResult'][0][0]['tgt']))
                a = a - 1

結果為:

      JSON是一種輕量級的數據交換格式,我們需要在爬取到的內容中找到JSON格式的數據,再將得到的JSON格式的翻譯結果進行解析。

     總而言之,這部分的內容我終於結束了,debug太耗費時間了!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM