Python 幾種爬蟲的方法

2021-10-11 01:33:48 字數 1095 閱讀 6908

1.1安裝requests庫

pip install requests

1.2例項:

import requests

r = requests.get(url)

print r.text

print r.status_code

傳遞url引數

import requests

key_dict =

r = requests.get(url,params=key_dict)

定製請求頭

import requests

headers =

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

print (「響應狀態碼:」,r.status_code)

2.1安裝selenium

pip install selenium

示例:from selenium import webdriver

driver = webdriver.firefox()

driver.get(url)

遇到的問題:

1.python2和3中』ascii』 codec can』t decode position 0: ordinal not in range(128)

python2:

在開頭加上

import sys

reload(sys)

sys.setdefaultencoding(『utf-8』)

python3:

x = pickle.load(open("./data/coco/word2vec.p",「rb」),encoding=『bytes』)

2.使用demjson

pip install demjson

demjson.encode --將物件轉換json

demjsonl.decode --將json轉化為物件

3.print ()

使用i = cool

print(「中文測試:」 + i )

使用上述方法容易亂碼

可以使用:

print (「中文測試 %s」) % i

解決

Python爬蟲,get方法的封裝

這裡比較規範的使用了工程化的思想,考慮了日誌的編寫 爬蟲傳送get請求時,則考慮了ua等http request head部分的設定 並且支援 伺服器的資訊處理 返回的狀態碼不是200時的處理 並且考慮了超時問題,及網頁的編碼問題 import sys import logging import u...

python的幾種常見排序方法

簡單交換排序 n int input 請輸入需要排序的資料個數 x for i in range n for i in range n 1 for j in range i 1,n if x i x j x i x j x j x i 每次符合結果的都進行資料交換 print 排序後的資料 x 氣泡...

Python幾種讀檔案的方法

python幾種讀檔案的方法 f open filepath r encoding utf 8 一行行的讀出 for line in f print line file.read size 從檔案讀取指定的位元組數,如果未給定或為負則讀取所有。fo open runoob.txt rw print ...