天天看點

一、通過Requests子產品擷取網頁内容并使用BeautifulSoup進行解析

這是Python爬蟲系列文章第一篇

首先列一下爬蟲的四個基本步驟

1.擷取資料
2.解析資料
3.提取資料
4.存儲資料
           

下面從最基本的擷取資料開始講起

1、擷取内容

import requests
response = requests.get('url')
# requests.get是在調用requests庫中的get()方法,它向伺服器發送了一個請求,
# 括号裡的參數是你需要的資料所在的網址,然後伺服器對請求作出了響應。
# 我們把這個響應傳回的結果指派在變量res上。
           

response的常用屬性:

屬性 作用
response.status_code 檢查請求是否成功
response.content 把response對象轉換為二進制資料
response.text 把response對象轉換為字元串資料
response.encoding 定義response對象的編碼

example圖檔下載下傳

import requests
res = resuqests.get('https://avatar.csdn.net/3/C/B/3_liusuxilinyue.jpg')
#上面的url就是我的部落格的頭像
file = open('photo.jpg','wb')
file.write(res.content)
file.close
           

2、使用BeautifulSoup解析資料和提取資料

BeautifulSoup需要進行安裝,因為不是python自帶的,pip install BeautifulSoup4
基本解析方式		bs = BeautifulSoup(要解析的字元串文本,'解析器')
           

解析資料

import requests
from bs4 import BeautifulSoup
res = requests.get('url')
html = res.text
bs = BeautifulSoup(html,'html.parser')
           

提取資料

方法 作用 用法 示例
find() 提取滿足要求的首個資料 BS對象.find(标簽,屬性) soup.find(‘div’,class_=‘books’)
find_all() 提取滿足要求的所有資料 BS對象.find_all(标簽,屬性) soup.find_all(‘div’,class_=‘books’)

這樣提取出來還是tag對象,需要進一步提取

Tag對象的三種常用屬性和方法

屬性/方法 作用
Tag.find()/Tag.find_all() 提取tag中的tag,與bs對象一樣
Tag.text 提取Tag中的文字
Tag[‘屬性名’] 提取Tag中某個屬性的屬性值

上面整個可以歸納為以下圖檔形式

一、通過Requests子產品擷取網頁内容并使用BeautifulSoup進行解析

Example

import requests
# 引用requests庫
from bs4 import BeautifulSoup
# 引用BeautifulSoup庫

res_foods = requests.get('http://www.xiachufang.com/explore/')
# 擷取資料
bs_foods = BeautifulSoup(res_foods.text,'html.parser')
# 解析資料

tag_name = bs_foods.find_all('p',class_='name')
# 查找包含菜名和URL的<p>标簽
tag_ingredients = bs_foods.find_all('p',class_='ing ellipsis')
# 查找包含食材的<p>标簽
list_all = []
# 建立一個空清單,用于存儲資訊
for x in range(len(tag_name)):
# 啟動一個循環,次數等于菜名的數量
    list_food = [tag_name[x].text[18:-14],tag_name[x].find('a')['href'],tag_ingredients[x].text[1:-1]]
    # 提取資訊,封裝為清單。注意此處[18:-14]切片和之前不同,是因為此處使用的是<p>标簽,而之前是<a>
    list_all.append(list_food)
    # 将資訊添加進list_all
print(list_all)
# 列印
           

這篇文章先寫到這,其實這時簡單的靜态網頁已經可以爬取下來了,隻是還需要進行存儲操作,這裡存儲放到下一篇進行講解。