数据解析
- response 方法
- content 返回二进制响应数据
- text 返回字符串
- json() 返回json对象
正则
- re.S 单行匹配
- re.M 多行匹配
img_src_list = re.findall(ex,img_data,re.S)
bs4数据解析
数据解析的原理
- 1.标签定位
- 2.提取标签、标签属性中存储的数据值
bs4数据解析的原理:
- 1.实例化一个BeautifulSoup对象,并将页面源码数据加载到该对象中
- 2.通过调用BeautifulSoup对象中相关的属性或者方法进行标签定位和数据提取
对象的实例化:
- 本地html文档数据加载
- fp = open(\'xx.html\',\'r\',encoding = \'utf-8\')
- soup = BeautifulSoup(fp,\'lxml\')
- 页面源码加载
- page_text = response.text
- soup = BeautifulSoup(page_text,\'lxml\')
- 使用lxml解析器
bs4方法属性
- soup.tagName 返回第一次出现的tagName标签
-print(soup.a)\soup.div\soup.p ... - soup.find(\'div\')
- 等同于soup.div\print(soup.find(\'div\'))
- 属性定位
- soup.find(\'div\',class_/id/attr = \'xxx\')
- 返回目标标签
- soup.findall(\'tagName\')
- 返回符合要求的所有标签(列表)
- soup.select()
- 类选择器 soup.select(\'.xxx\'),(\'.\'类选择器)
- id,class, 标签...选择器,(返回列表)
- 标签选择soup.select(\'xxx\')
- 层级选择器
- soup.select(\'.xxx > div > l > a\')[0] //>表示的是一个层级
- soup.select(\'.xxx > div a\')[0]空格表示多个层级
- 类选择器 soup.select(\'.xxx\'),(\'.\'类选择器)
- 获取标签间文本数据
- soup.a.text/string/get_text()
- text/get_text() 可以获取一个标签中所有的文本内容(子标签)
- string 只可以获取标签下直系文本内容
- soup.a.text/string/get_text()
- 获取标签中的属性值
- soup.select(\'.xxx > div > l > a\')[0][\'href\']
xpath解析
-
实例化etree对象
- tree = etree.parse(\'x.html\')//filepath
- tree = etree.HTML(\'xxx_text\')
-
标签定位 :
-
tree.xpath(\'/html/head/title\')
-
tree.xpath(\'/html//title\')
-
tree.xpath(\'//title\')
-
返回Element类型对象列表
-
/:表示的是从根节点进行定位,表示一个层级
-
//: 表示多个层级,可以表示从任意位置开始定位\'//div\'
-
-
属性定位
- tree.xpath(\'//div[@class="ss"]\')
-
索引定位
- tree.xpath(\'//div[@class="ss"]/p[3]\') 索引从1开始
-
取文本
- /text() 获取标签中直系的文本内容
- //text() 标签中非直系文本内容(所有文本内容)
-
取属性
- /@attrName ==>img/src
-
tree.xpath(\'/html/head/title | //title\') // \'|\' 将多个结果合并
-
tree.xpath 返回etree类型列表 可对子tree进行xpath解析 \'./\'继承父结果
-
city_name_list = tree.xpath(\'//div[@class="bottom"]/ul/li\') for city in city_name_list: c = city.xpath(\'./a/text()\') #相当于\'//div[@class="bottom"]/ul/li/a/text()\'
-
-编码错误解决方法
- encode(\'iso-8859-1\').decode(\'gbk\')
- encode(\'iso-8859-1\').decode(\'utf-8\')