域名查詢網(wǎng)站百度seo整站優(yōu)化
bs4介紹和遍歷文檔樹
BeautifulSoup 是一個可以從HTML或XML文件中提取數(shù)據(jù)的Python庫,解析庫
需要安裝模塊:pip install beautifulsoup4
使用
解析庫可以使用 lxml,速度快(必須安裝) 可以使用python內(nèi)置的
# html_doc爬出的網(wǎng)頁text
soup = BeautifulSoup(html_doc, 'html.parser')
重點:遍歷文檔樹
遍歷文檔樹:即直接通過標簽名字選擇,特點是選擇速度快,但如果存在多個相同的標簽則只返回第一個
- 用法:通過
.
遍歷# 拿到 以下的第一個title res=soup.html.head.title# 拿到第一個p res=soup.p
- 取標簽的名稱
res=soup.html.head.title.name res=soup.p.name
- 獲取標簽的屬性
# 標簽的所有屬性 res=soup.body.a.attrs # 所有屬性放到字典中 :{'href': 'http://example.com/elsie', 'class': ['sister'], 'id': 'link1'}# 獲取第一個屬性值 res=soup.body.a.attrs.get('href') res=soup.body.a.attrs['href'] res=soup.body.a['href']
- 獲取標簽的內(nèi)容
res=soup.body.a.text res=soup.p.text# 這個標簽有且只有文本,才取出來,如果有子孫,就是None res=soup.a.string res=soup.p.strings
- 嵌套選擇
就是通過.
嵌套
- 子節(jié)點、子孫節(jié)點
#p下所有子節(jié)點 print(soup.p.contents)#得到一個迭代器,包含p下所有子節(jié)點 print(list(soup.p.children)) #獲取子子孫節(jié)點,p下所有的標簽都會選擇出來 print(list(soup.p.descendants))
- 父節(jié)點、祖先節(jié)點
#獲取a標簽的父節(jié)點 print(soup.a.parent)#找到a標簽所有的祖先節(jié)點,父親的父親,父親的父親的父親... print(list(soup.a.parents) )
- 兄弟節(jié)點
print(soup.a.next_sibling) #下一個兄弟 print(soup.a.previous_sibling) #上一個兄弟 print(list(soup.a.next_siblings)) #下面的兄弟們=>生成器對象 print(soup.a.previous_siblings) #上面的兄弟們=>生成器對象
搜索文檔樹
find_all
:找所有 列表find
:找一個 Tag類的對象
find和find_all
五種過濾器: 字符串、正則表達式、列表、True、方法
字符串
可以按標簽名,可以按屬性,可以按文本內(nèi)容
無論按標簽名,按屬性,按文本內(nèi)容 都是按字符串形式查找
# 找到類名叫 story的p標簽
p=soup.find('p')# 可以按標簽名,可以按屬性,可以按文本內(nèi)容
p=soup.find(name='p',class_='story')
obj=soup.find(name='span',text='lqz')
obj=soup.find(href='http://example.com/tillie')# 屬性可以寫成這樣
obj=soup.find(attrs={'class':'title'})
正則
無論按標簽名,按屬性,按文本內(nèi)容 都是按正則形式查找
import re# 找到所有名字以b開頭的所有標簽
obj=soup.find_all(name=re.compile('^b'))# 以y結(jié)尾
obj=soup.find_all(name=re.compile('y$'))obj=soup.find_all(href=re.compile('^http:'))
obj=soup.find_all(text=re.compile('i'))
列表
無論按標簽名,按屬性,按文本內(nèi)容 都是按列表形式查找
# 所有a標簽和標簽放到一個列表里
obj=soup.find_all(name=['p','a'])
obj = soup.find_all(class_=['sister', 'title'])
True
無論按標簽名,按屬性,按文本內(nèi)容 都是按布爾形式查找
obj=soup.find_all(id=True)
obj=soup.find_all(href=True)
obj=soup.find_all(name='img',src=True)
方法
無論按標簽名,按屬性,按文本內(nèi)容 都是按方法形式查找
## 有class但沒有id
def has_class_but_no_id(tag):return tag.has_attr('class') and not tag.has_attr('id')print(soup.find_all(name=has_class_but_no_id))
案例:爬美女圖片
import requests
from bs4 import BeautifulSoupres = requests.get('https://pic.netbian.com/tupian/32518.html')
res.encoding = 'gbk'soup = BeautifulSoup(res.text, 'html.parser')ul = soup.find('ul', class_='clearfix')
img_list = ul.find_all(name='img', src=True)for img in img_list:try:url = img.attrs.get('src')if not url.startwith('http'):url = 'https://pic.netbian.com' + urlres1 = requests.get('url')name = url.split('-')[-1]with open('./img/%s' % name, 'wb') as f:for line in res1.iter_content():f.write(line)except Exception as e:continue
bs4其它用法
-
遍歷,搜索文檔樹 ? \dashrightarrow ? bs4還可以修改xml
- java的配置文件一般喜歡用xml寫
- .conf
- .ini
- .yaml
- .xml
-
find_all 其他參數(shù)
limit=數(shù)字
找?guī)讞l ,如果寫1 ,就是一條recursive
:默認是True,如果改False,在查找時只查找子節(jié)點標簽,不再去子子孫孫中尋找
-
搜索文檔樹和遍歷文檔樹可以混用,找屬性,找文本跟之前學(xué)的一樣
css選擇器
- id選擇器:
#id號
- 標簽選擇器:
標簽名
- 類選擇器:
.類名
- 屬性選擇器
需要記住的
#id
.sister
head
div>a
:# div下直接子節(jié)點adiv a
:div下子子孫孫節(jié)點a
一旦會了css選擇器的用法 ? \dashrightarrow ? 以后所有的解析庫都可以使用css選擇器去找
查找:p=soup.select('css選擇器')
復(fù)制參考:https://www.runoob.com/cssref/css-selectors.html
案例
import requests
from bs4 import BeautifulSoupres = requests.get('https://www.cnblogs.com/liuqingzheng/p/16005896.html')
soup = BeautifulSoup(res.text, 'html.parser')# 以后直接復(fù)制即可
p = soup.select('a[title="下載嗶哩嗶哩視頻"]')[0].attrs.get('href')
print(p)