美文网首页Python
[Python] BeautifulSoup使用

[Python] BeautifulSoup使用

作者: 半为花间酒 | 来源:发表于2020-04-09 10:59 被阅读0次

内容参考:4.2-使用Beautiful Soup(崔庆才)

内容是以前的学习笔记,内容不全,主观性较大,欢迎参考

解析器

from bs4 import BeautifulSoup

soup = BeautifulSoup(html_data,'lxml') #解析器中'lxml'快,'html.parser'内置较快
print(soup.prettify())  # 整理成清晰标准的文档树,遗失的根元素会补齐并转小写

find() / find_all()

find_all(self,name=None,attrs={},recursive=True,text=None,limit=None,**kwargs)

  1. name: 要查找的tag标签名称,默认为None,即查找所有元素

    tag = soup.find('p')

  2. attrs: 查找含有指定属性的元素,字典形式

    tag = soup.find_all('p',attrs={'class':'title'})

    也可以不用字典形式直接传入

    tag = soup.find(class_ = 'title')

  3. recursive: 是否在元素节点子树下全范围查找,默认是True

tips:

  • 查找完成后需要获取元素某个属性:

    tag['href'] # 即tag[attrs]

    (注意:tag['class']返回的不是字符串而是列表)

text = "<div class = 'style xxx'>"

tag = soup.find('div')  # 也可写作 tag = soup.div
tag['class'] == ['style','xxx']
  • 查找完成后需要获取元素名称:

    tag.name

  • 查找完成后需要获取元素文本(也包含所有子孙节点文本):

    tag.text
    tag.string
    tag.get_text()

  • 查找完成后判断元素是否含某个属性:

    tag.has_attr('href')

  • 查找完成后是多个节点的生成器列表:

    list(tag)[0].text
    list(tag)[0].attrs['class']

自定义函数高级查找

def myFilter(tag)
    results = tag.name=='a' and tag.has_attr['href'] and tag['href']==''
    return results

soup = BeautifulSoup(html_data,'lxml')
tag = soup.find_all(myFilter)
print(tag)

CSS选择器

tag.select(CSS)

返回的是bs4.element.Tag的列表

  • soup.select(div p)

    查找<div>下面所有子孙节点<p>

  • soup.select(div > p)

    查找<div>下面所有直接子节点<p>,'>'前后必须有空格

  • soup.select(div > p:nth-of-type(3))

    查找<div>下面第三个直接子节点<p>

  • soup.select(p[class = 'title style'] a)

    查找所有含有class='title'的<p>节点下的所有<a>节点

    也可以写为soup.select(p.title.style a)

  • soup.select(p [class] a)

    查找所有<p>节点下所有具有class属性节点下的所有<a>节点

  • soup.select(div ~ p)

    查找<div>所有同级别兄弟节点<p>,'~'前后必须有空格

  • soup.select(div + p)

    查找<div>后面第一个同级别兄弟节点<p>,'+'前后必须有空格

属性的语法规则:

选择器 描述
[attrs ^= value] 匹配属性值以指定值开头的每个元素
[attrs $= value] 匹配属性值以指定值结尾的每个元素
[attrs *= value] 匹配属性值中包含指定值的每个元素

遍历HTML树

  • 所有父节点
tag = soup.find('p')
while tag:
    print(tag.name)
    tag = tag.parent
  • 所有直接子节点
tag = soup.find('p')
for x in tag.children:
    print(x.name)
  • 所有子孙节点
tag = soup.find('p')
for x in tag.desendants:
    print(x)  # 子孙节点包括text等
  • 临近兄弟节点
  1. 前一个兄弟节点:

tag.previous_sibling

  1. 后一个兄弟节点:

tag.next_sibling

UnicodeDammit()

属于bs4库,用于识别response文本的编码并转换

from bs4 import UnicodeDammit

Dammit = UnicodeDammit(data,['utf-8','gbk']) # 识别
data = Dammit.unicode_markup # 转换

可用下列代码识别编码

from bs4 import BeautifulSoup
import urllib.request

content = urllib.request.urlopen(url)
soup = BeautifulSoup(content)
print(soup.original_encoding)
# > utf-8

相关文章

网友评论

    本文标题:[Python] BeautifulSoup使用

    本文链接:https://www.haomeiwen.com/subject/zxpqmhtx.html