html中的結構可能是棵樹,不一定是二叉樹,可能是多叉的。這時用xpath定位,解析會比較合適。
語法:
1.解析本地儲存
tree=etree.parse('filename')
2.解析網上爬取
tree=etree.html(page_text)
3.標籤定位
tree.xpath('html/head') 定位到head標籤
tree.xpath('//head') 定位所有的head
tree.xpath('//li[3]') 定位到第三個
4.資料提取
tree.xpath('//a[@id="feng"]/text()')
tree.xpath('//div[@class="song"]//text()')
from lxml import etree
import requests
import os
#新建資料夾
new_url=format(url%page) #非第一頁的url
response=requests.get(new_url,headers=headers) #得到網頁的內容
response.encoding='gbk' #處理亂碼
page_text=response.text
tree=etree.html(page_text)
li_list=tree.xpath('//div[@class="slist"]/ul/li')#定位到所有的li標籤
with open(filepath,'wb') as fp: #寫入檔案
fp.write(img_data)
print(img_src,img_name)
python爬蟲資料解析之bs4
步驟 1 匯入bs4庫 from bs4 import beautifulsoup2 獲取soup物件 html為你獲取的網頁源 將html轉化為特定的格式lxml 為後面提取資訊做準備 soup beautifulsoup html,lxml 3 利用方法選擇器解析 find all 查詢所有符合...
python爬蟲bs4 xpath資料解析
在爬取網頁後,通常需要將爬取到的內容進行分割提取,拿到我們想要的文字內容或者相應的位址url。安裝bs4模組,並匯入 from bs4 import beautifulsoupfp open test.html r encoding utf 8 將本地的html文件中的資料記載到該物件中 soup ...
python爬蟲 資料解析
解析的區域性的文字內容都會在標籤之間或者標籤對應的屬性中進行儲存 使用正規表示式,利用字串匹配篩選出所需要的內容 例 ex re是python中使用正規表示式的庫 page text是爬取到頁面的原始碼 使用上面定義的正則匹配規則進行解析,得到的url img src list re.findall...