requests與BeautifulSoup基礎入門
1. 前言
最近在學習python爬蟲,以前實現python爬蟲,主要是使用較為底層的urllib和urllib2來實現的,這種方法最原始,編碼起來也比較困難。而采用requests + BeautifulSoup的實現方案,可以簡化代碼的書寫。如果有不好和錯誤的地方希望大佬指出。
2. 介紹
- 在使用這兩個模塊之前,需要對這兩個模塊做一些介紹:requests是基于urllib,采用 Apache2 Licensed 開源協議的 HTTP 庫,比 urllib 更加方便。BeautifulSoup是一個可以從HTML或XML文件中提取數據的Python庫,實際上,它將html中的tag作為樹節點進行解析。
- requests官方文檔:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
- BeautifulSoup官方文檔:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
3. 實現代碼
首先是引入這2個庫,這里我使用的是PyCharm編輯器,通過Settings→Project: WorkSpace→Project Interpreter尋找bs4和requests庫。pip方法引入第三方庫請自行百度。
先從最簡單的開始,點進糗事百科首頁
import requests # 導入requests模塊
res = requests.get("http://www.qiushibaike.com") # 獲取糗事百科首頁
print (res.text) # print(res)打印的是響應碼,print(res.text)打印的是首頁的源代碼
得到頁面源碼,如果發現頁面文字是亂碼,則是編碼的原因,輸出頁面的編碼
print (res.encoding)
如果不是UTF-8,可以設置為UTF-8
res.encoding = "utf-8"
點進一篇文章,按F12進入開發者工具,按住ctrl+shift+c或者是點擊左上角的剪頭選中頁面中的文章
發現其class是content
# 獲取文章內容
import requests
from bs4 import BeautifulSoup
res = requests.get("https://www.qiushibaike.com/article/119567920")
soup = BeautifulSoup(res.text, "html.parser") # 把我們需要的內容放到BeautifulSoup中,html.parser是一個解析器
div = soup.find_all(class_="content")[0] # 找尋class為content的內容
print(div.text.strip()) # 輸出文章內容
如果要獲取首頁一頁的文章內容,則通過開發者工具查看首頁,發現每個文章的頁面class為article block untagged mb15 typs_xxxx
用re來匹配各種文章的class。
Python3正則表達式:http://www.runoob.com/python3/python3-reg-expressions.html
# 獲取所有文章的內容
import requests
from bs4 import BeautifulSoup
import re
res = requests.get("http://www.qiushibaike.com")
soup = BeautifulSoup(res.text, "html.parser")
divs = soup.find_all(class_=re.compile(r'article block untagged mb15 typs_(\w*)')) # 所有文章是一個數組
for div in divs: # 循環取出
joke = div.span.get_text()
print(joke.strip())
print("------")
輸出內容后發現有些內容讀起來很奇怪,看頁面發現有些是有圖片的,圖片的網頁標簽(HTML tag)是img。
所以我們要把有圖片的文章過濾掉,發現有圖片文章有個class為thumb,則我們把有圖片的過濾掉
# 獲取一頁沒有圖片的文章
import requests
from bs4 import BeautifulSoup
import re
res = requests.get("http://www.qiushibaike.com")
soup = BeautifulSoup(res.text, "html.parser")
divs = soup.find_all(class_=re.compile(r'article block untagged mb15 typs_(\w*)')) # 匹配class
for div in divs:
if div.find_all(class_="thumb"): # 如果有圖片則過濾
continue
joke = div.span.get_text()
print(joke.strip())
print("------")
但是糗事百科有很多頁,點擊第二頁發現網址為:https://www.qiushibaike.com/8hr/page/2/ ,點擊第三頁發現網址為:https://www.qiushibaike.com/8hr/page/3 ,所以我們只需要將網址最后的數字變動即可得到其他頁面
# 獲取前幾頁的文章
import requests
from bs4 import BeautifulSoup
import re
base_url = "https://www.qiushibaike.com/8hr/page/"
for num in range(1, 3): # 設置循環,讓num分別等于1-3,獲取前3頁內容
print('第{}頁:'.format(num))
res = requests.get(base_url + str(num)) # 這里對網址后面加上數字
soup = BeautifulSoup(res.text, "html.parser")
divs = soup.find_all(class_=re.compile(r'article block untagged mb15 typs_(\w*)'))
for div in divs:
if div.find_all(class_="thumb"):
continue
joke = div.span.get_text()
print(joke.strip())
print("------")
print("\n\n\n\n\n\n\n")