Python中BeautifulSoup4库的find_all、select用法等

Python中BeautifulSoup库的find_all、select用法等

  • 创建beautifulsoup对象
  • 解析html节点(find、find_all)
    • 传入函数
    • 根据节点属性值找到节点:
    • find_all参数
  • css选择器
    • tag对象
  • 直接获取标签(不推荐)

python中Bs4这个包是用来解析网页源码的包,爬虫程序常用这个包解析爬取网页源码进行分析,今天主要介绍这个包的一些基本使用。自行安装
可以直接查看官方文档: https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/

创建beautifulsoup对象

from bs4 import BeautifulSoup
import requests

headers = {
'Referer': 'https://hz.qk365.com/list/',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
}
base_url = 'https://www.baidu.com'  # 这个是你要爬的网址

response = requests.get(url=base_url, headers=headers)
# print(response.text)
soup = BeautifulSoup(html_str, 'lxml')

创建完成可以自行打印内容和tpye看看

解析html节点(find、find_all)

  • find:返回第一个符合条件的节点
  • find_all:以列表形式将符合条件的节点全部返回
# find_all可以传入字符串,正则表达式,列表(用于多个标签)
# 查找所有这个class的内容,返回为列表
print(soup.find_all(class_='easyList'))
# re匹配已d开头的内容
print(soup.find_all(re.compile('^d')))
# 列表多个查询
print(soup.find_all(['img', 'a']))
# text搜索
print(soup.find_all(text='租房'))

传入函数

查找有class和name属性的标签

soup=BeautifulSoup(html,'html.parser')
def condition(tag):
    return tag.has_attr('class') and  tag.has_attr('name')
print soup.find_all(condition)

根据节点属性值找到节点:

import re
soup=BeautifulSoup(html,'html.parser')
print soup.find_all(id='link1')
print soup.find_all(href=re.compile(r'lacie'))
print soup.find_all(class_='sister' ,id='link3')
print soup.find_all('a',id='link3')
print soup.find_all(attrs={"id":'link3','class':'sister'})

find_all参数

  • limit 参数
  • soup.find_all(“a”, limit=2)#对筛选结果筛选两个内容
  • recursive 参数
  • soup.html.find_all(“b”)#默认搜索结果范围是子孙节点
  • soup.html.find_all(“b”,
    recursive=False)#设置recursive此参数后搜索结果范围只为子节点
  • text参数是搜索
  • attrs参数是根据属性查询

css选择器

方法 内容
通过标签名查找 soup.select(‘title’)#直接原值表示标签名
通过类名查找 soup.select(’.sister’)#.加值代表类名
通过id查找 soup.select(’#link1’)##字符代表id
组合查找 print soup.select(‘p #link1’)#p标签且id为link1得对象
标签依次查询 soup.select(“head > title”)#head标签下得title标签
通过href属性查找 soup.select(‘p a[href=“http://example.com/elsie”]’)#p标签下a属性得href值*对象

tag对象

根据选择器查询返回为列表,列表里的内容是tag对象
tag对象获取属性:tag.attrs[‘href’]
tag对象获取标签文字内容:tag.get_text()

直接获取标签(不推荐)

获取标签:

soup.head(获取第一个head标签)

soup.head.title(获取head标签下面的第一个title标签)

获取标签名称:

soup.head.name

获取标签文本:

soup.title.tex#t获取title标签的文本标签

soup.title.string#获取title标签的文本标签;如果标签i里面有子节点,则无法获取内容打印None,因为不知道打印那个节点的文本

获取标签属性:

soup.p.attrs#获取p标签的所有属性,以字典形式返回

soup.p[‘class’]#获取p标签的class属性的值

你可能感兴趣的:(爬虫)