bs4解析
bs4:
- 環境安裝:
- lxml
- bs4
- bs4編碼流程:
- 1.實例化一個bs4對象,且將頁面源碼數據加載到該對象中
- 2.bs相關的方法或者屬性實現標簽定位
- 3.取文本或者取屬性
- bs的屬性和方法:
- soup.tagName
- tagName.string/text/get_text()
- tagName[attrName]
- find(tagName,attrName='value')
- select('層級選擇器') > 空格
- 環境的安裝:
- pip install lxml
- pip install bs4
- bs4解析原理:
- 實例化一個bs對象,且將頁面源碼數據加載到該對象中。
- 使用bs對象中封裝好的屬性或者方法實現標簽定位
- 將定位到的標簽中的文本(屬性)取出
用法:
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
}
#將本地的一個test.html文檔中的源碼數據加載到bs對象中
soup = BeautifulSoup(open('./test.html','r',encoding='utf-8'),'lxml')
soup.p #定位到源碼中第一個p標簽
soup.a['href'] #取屬性
soup.img['src']
# 取文本 返回字符串
soup.p.get_text()
# 取標簽
soup.div
#
soup.div.string #string直接獲取標簽的直系文本內容
soup.div.text # 取文本
soup.ul.text
# 查找 只查找第一個元素
soup.find('li') #soup.li
#屬性定位
soup.find('div',class_='song')
# 查找所有的 div標簽
soup.find_all('div')[0]
# 通過選擇器查找 返回列表
soup.select('#feng')
# 獲取 內容
soup.select('ul > li > a')[3].string
-
bs4 爬取某某詩詞網
#需求:某某詩詞網中的三國演義小說進行爬取:http://www.*****.com/book/sanguoyanyi.html
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
}
url = 'http://www.****.com/book/sanguoyanyi.html'
page_text = requests.get(url=url,headers=headers).text
#數據解析
soup = BeautifulSoup(page_text,'lxml')
#解析出章節和詳情頁的url
li_list = soup.select('.book-mulu > ul > li')
fp = open('./三國演義.txt','w',encoding='utf-8')
for li in li_list:
title = li.a.string
detail_url = 'http://www.**********.com'+li.a['href']
#獲取了詳情頁的頁面源碼數據
detail_page_text = requests.get(url=detail_url,headers=headers).text
soup = BeautifulSoup(detail_page_text,'lxml')
#解析出章節對應的內容
content = soup.find('div',class_='chapter_content').text
fp.write(title+'\n'+content)
print(title,'下載完畢')
fp.close()