BS4
BeautifulSoup是用来从HTML or XML中提取数据的Python lib。BeautifulSoup将文档转化为树形结构(DOM),每个节点都是下述四种类型的Python对象:
- BeautifulSoup
<class 'bs4.BeatifulSoup'>
- Tag
<class 'bs4.element.Tag'>
- NavigableString
<class 'bs4.element.NavigableString'>
- Comment
<class 'bs4.element.Comment'>
从集合角度理解以上4中类的关系(类概念上并不准确)
- BeautifulSoup 为全集(将Document以入参传入生成BeautifulSoup object), 包含 Tag子集
- Tag 包含 NavigableString 子集
- Comment 为 NavigableString 特殊集合
Usage
BeautifulSoup的第一个入参是Document,第二个入参指定Document parser 类型.
from bs4 import BeautifulSoup
import requests, re
url = 'http://m.kdslife.com/club/'
# get whole HTTP response
response = requests.get(url)
# args[0] is HTML document, args[1] select LXML parser. returned BeautifulSoup object
soup = BeautifulSoup( response.text, 'lxml')
print soup.name
# [document]'
print type(soup)
# <class 'bs4.BeatifulSoup'>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
Sample codes for Tag objects
# BeutifulSoup --> Tag
# get the Tag object(title)
res = soup.title
print res
# <title>KDS Life</title>
res = soup.title.name
print res
# title
# attribules of a Tag object
res = soup.section
print type(res)
# <class 'bs4.element.Tag'>
print res['class']
# ['forum-head-hot', 'clearfix']
# All the attributes of section Tag object, returned a dict
print res.attrs
#{'class': ['forum-head-hot', 'clearfix']}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
Sample codes for NavigableString object
# NavigableString object describes the string in Tag object
res = soup.title
print res.string
# KDS Life
print type(res.string)
# <class 'bs4.element.NavigableString'>
- 1
- 2
- 3
- 4
- 5
- 6
Sample codes for Comment object
# Comment, is a special NavigableString object
markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>"
soup = BeautifulSoup(markup)
comment = soup.b.string
print type(comment)
# <class 'bs4.element.Comment'>
- 1
- 2
- 3
- 4
- 5
- 6
BS4 Parser
按照优先顺序自动解析,’lxml’ –> ‘html5lib’ –> ‘html.parser’
常用Tag对象方法
find_all()
find_all(name,attrs,recursive,text,**kwargs)
不解释,直接看代码
# filter, returned a matching list
# returned [] if matching nothing
title = soup.find_all('title')
print title
#[<title>Google</title>]
res = soup.find_all('div', 'topAd')
print res
# find all the elements whose id is 'gb-main'
res = soup.find_all(id='topAd')
print res
#[<div id="topAd">...</div>]
# find all the elements with 'img' tag and 'src' attribute matching the specific pattern
res = soup.find_all('img', src=re.compile(r'^http://club-img',re.I))
print res
# [<img src="http://club-img.kdslife.com/attach/1k0/gs/a/o41gty-1coa.png@0o_1l_600w_90q.src"/>,
#...]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
select()
# css selector
# select those whose tag's id = wrapperto
res = soup.select('#wrapperto')
print res
# [<div class="swiper-wrapper clearfix" id="wrapperto"></div>]
# select those 'img' tags who have 'src' attribute
res = soup.select('img[src]')
print res
#[<img alt="" src="http://icon.pch-img.net/kds/club_m/club/icon/user1.png"/>, <im
#g src="http://club-img.kdslife.com/attach/1k0/gs/a/o41gty-1coa.png@0o_1l_600w_90q.src"/>]
# select those 'img' tags whose 'src' attribute is
res = soup.select('img[src=http://icon.pch-img.net/kds/club_m/club/icon/user1.png]')
print res
# [<img alt="" src="http://icon.pch-img.net/kds/club_m/club/icon/user1.png"/>]
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
Other
# get_text()
markup = '<a href="http://example.com/">\n a link to <i>example.com</i>\n</a>'
soup = BeautifulSoup(markup,'lxml')
res = soup.get_text()
print res
# a link to example.com
res = soup.i.get_text()
print res
# example.com
# .stripped_string
res = soup.stripped_strings
print list(res)
# [u'a link to', u'example.com']
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
最后贴上一个简单的KDS图片爬虫
Note
- BeautifulSoup进行了编码检测并自动转为Unicode. soup.original_encoding属性来获取自动识别编码的结果。
- Input converts to unicode, output encodes with utf-8
- 在BS使用中,可配合 XPath expression使用
http://blog.csdn.net/BruceXiaoYY/article/details/51587063
(二)
取值与赋值
从网页获取了需要的标签后,要做的就是从标签中获得需要的值了。
BS4的取值主要通过以下方法。
标签名
#获取标签名
tag.name
#对应的该变标签名为
tag.name = "你想要的标签"
- 1
- 2
- 3
- 4
属性
#获取属性
#获取属性列表
tag.attrs
#输出为一个dict键为属性,值为属性值
#例如{"class":"abc", "id":"link1"}
#获取指定属性
tag['class']
#或
tag.get('class')
#多值属性
#对于HTML中定义的一些可以包含多个值的属性(class,rev等等)
#返回值为list类型
tag['class']
#例如['top', 'box']
#为属性赋值
tag['class'] = "class1"
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
内容
这里用两种获取方式
.string 和 get_text()
.string 用来获取标签的内容
get_text() 用来获取标签中所有字符串包括子标签的。
#获取当前标签内容
tag.string
#返回结果的type为 <class 'bs4.element.NavigableString'>
#获取标签内所有的字符串
tag.get_text()
#返回结果的type为 <class 'str'>
#为标签内容赋值
tag.string = "str"
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
注意!!
在取值时我们要注意一点就是在获取标签的时候获取的是单个标签还是标签列表。
也就是find()和find_all(),select()和select_one()的区别。
当使用
find()
select_one()
- 1
- 2
时,获得的是一个标签
类型为
<class 'bs4.element.Tag'>
- 1
所以可以使用tag['class']
取值
当使用
find_all()
select()
- 1
- 2
时,获得的是组标签(就算只有一个标签也是一组)
类型为
#find_all()的返回值类型
<class 'bs4.element.ResultSet'>
#select()的返回值类型
<class 'list'>
- 1
- 2
- 3
- 4
这时,我们要取值就需要先定位是list(ResultSet)中的那个标签在取值
例如tag[0]['class']
http://blog.csdn.net/zjiang1994/article/details/52679174
https://cuiqingcai.com/
http://blog.csdn.net/xiu_star/article/details/70157924