Python-bs4解析html


Beautiful Soup簡介(簡稱bs4)

它是一個可以從HTML或XML文件中提取數據的Python庫,它能夠通過你喜歡的轉換器實現慣用的文檔導航、查找、修改文檔的方式,節省工作時間

 所有對象可以歸納為4種:

Tag:標簽對象,例如<p class=”title”><b>yoyoketang</b></p>,這就是一個標簽

NavigableString:字符對象,如:這里是我的微信公眾號:yoyoketagn

BeautifulSoup:就是整個html對象

Comment:注釋對象,如:!-- for HTML5 --,它其實就是一個特殊NavigableString

安裝pip install beautifulsoup4

1、通過標簽的名稱,來獲取tag對象,如果有多個相同的標簽名稱,返回的是第一個,soup.head

2、獲取標簽中的字符文本,soup.head.title.string

3、tag.attrs可以打印出所有的屬性,返回字典格式的,獲取其中的某個屬性,跟操作字典一樣,如:tag.attrs['href'] 或者 tag['href'],由於class屬性一般可以為多個,中間空格   隔開,所以class屬性獲取的是一個list類型

4、查找元素,find_all查找所有符合要求的,返回的是一個list對象

5、get_text()獲取tag標簽下所有的文本

6、replace替換字符串里面的特殊字符

練習一

from bs4 import BeautifulSoup
htmldemo = '''
<meta charset="UTF-8"><!-- for HTML5 -->
<meta http-equiv="Content-Type" content="text/html:charset=utf-8" />
<html><head><title>yoyoketang</title></head>
<body>
<b><!--Hey,this in comment!--></b>
<p class="title"><b>yoyoketang</b></p>
<p class="yoyo">這里是我的微信公眾號:yoyoketang<br>
<a href="http://www.cnblogs.com/yoyoketang/tag/fiddler/" class="sister name" id="link1"><m id='p'>la</m>fiddler教程</a><br>
<a href="http://www.cnblogs.com/yoyoketang/tag/python/" class="sister" id="link2">python筆記</a><br>
<a href="http://www.cnblogs.com/yoyoketang/tag/selenium/" class="sister" id="link3">selenium文檔</a><br>
快來關注吧!</p>
<p class="story">...</p>
'''
#html.parser是解析器
soup = BeautifulSoup(htmldemo, 'html.parser')
#獲取標簽head
print(soup.head)
#獲取字符
print(soup.head.title.string)
print(soup.a.attrs)
print(soup.a.attrs['href'])
print(soup.a['href'])
#根據class查找,不能直接用class查找 , class_='sister'
s = soup.find_all(class_='sister')
#二次查找
s2 = s[0].find_all(id='p')
#根據id查找
m = soup.find_all(id='link3')
#獲取標簽下的所有文本
t = soup.body.get_text()

練習二

from bs4 import BeautifulSoup
import requests
import os
#請求一個圖片地址,獲取其中所有的圖片url和title
r = requests.get('http://699pic.com/sousuo-218808-13-1.html')
soup = BeautifulSoup(r.content, 'html.parser')
images = soup.find_all(class_='lazy')
curpath = os.path.dirname(os.path.realpath(__file__))
for i in images:
jpg_url = i['data-original']
title = i['title']
print(jpg_url)
print(title)
print('')
#下載獲取到的圖片,下載到curpath,名字title.jpg
with open(curpath+'\\'+title+'.jpg','wb') as f:
f.write(requests.get(jpg_url).content)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM