解析库的使用XPath&Beau Soup

XPath

导入from lxml import etree
修正HTML文本etree.tostring(html)
修正编码tostring返回bytes类型,利用decode转成str
所有节点html.xpath('//*')
子节点选择li 节点的所有直接a子节点,
html.xpath('//li/a')
父节点

现在首先选中href 属性为link4.html 的a 节点,然后再获取其父节点,然后再获取其class属性

html.xpath(’//a[@href=”link4.html”] / .. /@class’)

html.xpath(’//a[@href=”link4.html“]/parent: :*/@class')

属性匹配

选取class 为item-1 的li节点

html. xpath('//li[@class =”item-1”]')

文本获取/text()
属性获取html. xpath (’//li/a/@href')
属性多值匹配html. xpath (’//li[contains(@class,”li”)]/a/text()’)
contains()方法,第一个参数传人属性名称,第二个参数传人属性值,只要此属性包含所传人的属性值,就可以完成匹配了。
多属性匹配html.xpath('//li[contains(@class,”li") and @name="item"]/a/text()')
按序选择

html. xpath (’//li[1]/a/text()’)

html.xpath(’//li[last()]/a/text()’)

节点轴选择

html. xpath (’//li[1]/ancestor::*’)

html. xpath (’//li[1]/ancestor : :div')

html.xpath(’//li[1]/attribute: : *’)

......

Beautiful Soup

一、基本用法

#,该对象的第二个参数为解析器的类型(这里使用lxml),此时就完成了BeaufulSoup 对象的初始化。
#然后,将这个对象赋值给soup 变量。
soup = BeautifulSoup(html,'lxml')
#调用prettify()方法。这个方法可以把要解析的字符串以标准的缩进格式输出。
print(soup.prettify())
#,soup.title
#可以选出HTML中的title节点,再调用string属性就可以得到里面的文本了
print(soup.title.string)

二、节点选择器

选择元素

#节点选择器
#直接调用节点的名称就可以选择节点元素,再调用string 属性就可以得到节点内的文本了
html = '''
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b> The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="linkl"><!--Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2"> Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well .</p>
<p class="story"> ... </p>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(soup.title)
print(type(soup.title))
print(soup.title.string)
print(soup.head)
print(soup.p)#当有多个节点时,这种选择方式只会选择到第一个匹配的节点,其他的后面节点都会忽略

提取信息

  • 获取名称
soup = BeautifulSoup(html,'lxml')
#获取名称,可以利用name 属性获取节点的名称
print(soup.title.name)
  • 获取属性
#获取属性,调用attrs获取所有属性:
print(soup.p.attrs)
print(soup.p.attrs['name'])
print(soup.p['name'])
print(soup.p['class'])
  • 获取内容

1.嵌套选择

#嵌套选择
#每一个返回结果都是bs4.element.Tag类型,
#它同样可以继续调用节点进行下一步的选择
html1='''
<html><head><title>the Dormouse's story</title></head>
<body>
'''
soup1 = BeautifulSoup(html1,'lxml')
print(soup1.head.title)
print(type(soup1.head.title))
print(soup1.head.title.string)

2.关联选择

#关联选择
#子节点和子孙节点
print(soup.p.contents) #contents属性得到的结果是直接子节点的列表

三、方法选择器

  • name
#name
print(soup.find_all(name='ul'))
print(type(soup.find_all(name='ul')[0]))
  • attrs
#attrs,传入属性来查询
print(soup.find_all(attrs={'id':'list-1'}))
print(soup.find_all(attrs={'name':'elements'}))

参数的类型是字典类型。比如,要查询id 为list-1 的节点,可以传入attrs ={’id’ :’list-1 '}的查询条件,得到的结果是列表形式,包含的内容就是符合id为list-1 的所有节点。

  • text
#text,匹配节点的文本,传入的形式可以是字符串,也可以是正则表达式
import re
from bs4 import BeautifulSoup
html1='''
<div class="panel">
<div class="panel-body">
<a>Hello,this is a link</a>
<a>Hello,this is a link,too</a>
</div>
</div>
'''
soup1 = BeautifulSoup(html1,'lxml')
print(soup1.find_all(text=re.compile('link')))

除了find_all()方法,还有find()方法,只不过后者返回的是单个元素,也就是第一个匹配的元素,而前者返回的是所有匹配的元素组成的列表。

from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(soup.find(name='ul'))
print(type(soup.find(name='ul')))
print(soup.find(class_='list'))

#find_parents():返回所有祖先节点
#find_parent():返回直接父亲节点
#find_next_siblings()返回后面所有的兄弟节点
#find_next_sibling()返回后面第一个兄弟节点
#find_previous_siblings()返回前面所有的兄弟节点
#find_previous_sibling()返回前面第一个兄弟节点
#find_all_next():返回节点后所有符合条件的节点
#find_next():返回第一个符合条件的节点
#find_all_previous():返回节点前所有符合条件的节点
#find_previous():后者返回第一个符合条件的节点

四、CSS选择器

使用css 选择器时,只需要调用select()方法,传人相应的css 选择器即可

from bs4 import BeautifulSoup
soup = BeautifulSoup(html,'lxml')
print(soup.select('.panel .panel-heading'))
print(soup.select('ul li'))
print(soup.select('#list-2 .element'))  #????
print(type(soup.select('ul')[0]))
  • 嵌套选择
#嵌套选择
for ul in soup.select('ul'):
    print(ul.select('li'))
  • 获取属性
#获取属性
for ul in soup.select('ul'):
    print(ul['id'])
    print(ul.attrs['id'])
  • 获取文本
#获取文本
for li in soup.select('li'):
    print('GET TEXT:',li.get_text())
    print('String:',li.string)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值