1. 程式人生 > >網路爬蟲實戰(5個案例)

網路爬蟲實戰(5個案例)

案例1:京東商品頁面的爬取

商品連結

import requests
url = "https://item.jd.com/2967929.html"
try:
    r = requests.get(url)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    print(r.text[:1000])
except:
    print("爬取失敗")

案例2:亞馬遜商品頁面的爬取

商品連結

import requests
url = "https://www.amazon.cn/gp/product/B01M8L5Z3Y"
try:
    kv = {'user-agent':'Mozilla/5.0'}
    r = requests.get(url, headers = kv)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    print(r.text[1000:2000])
except:
    print("爬取失敗")

案例3:百度360關鍵詞提交

搜尋引擎關鍵詞提交介面

百度的關鍵詞介面:http://www.baidu.com/s?wd=keyword
360的關鍵詞介面:http://www.so/com/s?q=keyword

import requests
keyword = "Python"
try:
    kv = {'wd':keyword}
    r = requests.get("http://www.baidu.com/s",params=kv)
    print(r.request.url)
    r.raise_for_status()
    print(len(r.text))
except:
    print("爬取失敗")
import requests
keyword = "Python"
try:
    kv = {'q':keyword}
    r = requests.get("http://www.so.com/s",params=kv)
    print(r.request.url)
    r.raise_for_status()
    print(len(r.text))
except:
    print("爬取失敗")

案例4:網路圖片的爬取和儲存

網路圖片連結的格式:http://www.example.com/picture.jpg
國家地理
選擇一個圖片Web頁面:
http://www.nationalgeographic.com.cn/photography/photo_of_the_day/3921.html


該圖片地址:http://image.nationalgeographic.com.cn/2017/0211/20170211061910157.jpg

import requests
import os
url = "http://image.nationalgeographic.com.cn/2017/0211/20170211061910157.jpg"
root = "D://pics//"
path = root + url.split('/')[-1]
try:
    if not os.path.exists(root):
        os.mkdir(root)
    if not os.path.exists(path):
        r = requests.get(url)
        with open(path, 'wb') as f:
            f.write(r.content)
            f.close()
            print("檔案儲存成功")
    else:
        print("檔案已存在")
except:
    print("爬取失敗")

案例5:IP地址歸屬地的自動查詢

http://m.ip138.com/ip.asp?ip=ipaddress

import requests
url = "http://m.ip138.com/ip.asp?ip="
try:
    r = requests.get(url + '202.204.80.112')
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    print(r.text[-500:])
except:
    print("爬取失敗")

在學習中有迷茫不知如何學習的朋友小編推薦一個學Python的學習q u n 227  -435-  450可以來了解一起進步一起學習!免費分享視訊資料