爬蟲 資料解析 bs4

2022-05-17 02:28:10 字數 1861 閱讀 8196

正規表示式實現資料解析

# 需求:爬取糗事百科中糗圖資料

import requests

headers =

#方式1:

url = ''

img_data = requests.get(url=url,headers=headers).content #content返回的是byte型別的資料

#方式2:

- 方式2不可以使用ua偽裝的機制

- urllib就是乙個比較老的網路請求的模組,在requests模組沒有出現之前,請求傳送的操作使用的都是urllib

bs4 的解析原理

如何例項化beautifulsoup物件

標籤定位:

選擇器定位:select('選擇器'),返回值為列表

from bs4 import beautifulsoup

fp = open('./test.html','r',encoding='utf-8')

soup = beautifulsoup(fp,'lxml') #將即將被解析的頁面原始碼載入到該物件中

soup.p

soup.find('div',class_='song')

soup.find_all('div',class_='song')

soup.select('.tang')

soup.select('#feng')

soup.select('.tang > ul > li')

soup.select('.tang li')

li_6 = soup.select('.tang > ul > li')[6]

i_tag = li_6.i

i_tag.string

soup.find('div',class_='tang').text

soup.find('a',id="feng")['href']

提取資料

取屬性:

# 爬取三國演義整篇**內容

url = ''

page_text = requests.get(url,headers=headers).text

soup = beautifulsoup(page_text,'lxml')

a_list = soup.select('.book-mulu > ul > li > a')

fp = open('sanguo.txt','w',encoding='utf-8')

for a in a_list:

detail_url = ''+a['href']

chap_title = a.string

#對章節詳情頁的url發起請求,解析詳情頁中的章節內容

detail_page_text = requests.get(detail_url,headers=headers).text

soup = beautifulsoup(detail_page_text,'lxml')

chap_content = soup.find('div',class_="chapter_content").text

fp.write(chap_title+':'+chap_content+'\n')

print(chap_title,'爬取成功!')

fp.close()

python爬蟲資料解析之bs4

步驟 1 匯入bs4庫 from bs4 import beautifulsoup2 獲取soup物件 html為你獲取的網頁源 將html轉化為特定的格式lxml 為後面提取資訊做準備 soup beautifulsoup html,lxml 3 利用方法選擇器解析 find all 查詢所有符合...

python爬蟲學習(十)bs4解析資料

lxml安裝是個坑 coding utf 8 import lxml import requests from bs4 import beautifulsoup if name main ua偽裝 將對應的user agent封裝到字典中 headers url 對指定url發起請求,對應的url是...

爬蟲架構 bs4

方便解析html xml等格式的原始碼,快速查詢 修改等操作,節省數小時乃至更多的工作時間 官網文件 from bs4 import beautifulsoup print path beautifulsoup path 非真實網頁 html doc 夏日炎炎,要你幹嘛 print soup.hea...