详解BeautifulSoup获取特定标签下内容的方法

以下是个人在学习beautifulSoup过程中的一些总结,目前我在使用爬虫数据时使用的方法的是:先用find_all()找出需要内容所在的标签,如果所需内容一个find_all()不能满足,那就用两个或者多个。接下来遍历find_all的结果,用get_txt()、get(‘href')、得到文本或者链接,然后放入各自的列表中。这样做有一个缺点就是txt的数据是一个单独的列表,链接的数据也是一个单独的列表,一方面不能体现这些数据之间的结构性,另一方面当想要获得更多的内容时,就要创建更多的空列表。

遍历所有标签:

soup.find_all('a')

找出所有页面中含有标签a的html语句,结果以列表形式存储。对找到的标签可以进一步处理,如用for对结果遍历,可以对结果进行purify,得到如链接,字符等结果。

# 创建空列表
links=[]
txts=[]
tags=soup.find_all('a')
for tag in tags:
  links.append(tag.get('href')
  txts.append(tag.txt)         #或者txts.append(tag.get_txt())

得到html的属性名:

atr=[]
tags=soup.find_all('a')
for tag in tags:
  atr.append(tag.p('class')) # 得到a 标签下,子标签p的class名称

find_all()的相关用法实例:

实例来自BeautifulSoup中文文档

1. 字符串

最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的标签:

soup.find_all('b')
# [<b>The Dormouse's story</b>]

2.正则表达式

如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 match() 来匹配内容.下面例子中找出所有以b开头的标签,这表示和标签都应该被找到:

import re
for tag in soup.find_all(re.compile("^b")):
  print(tag.name)
# body
# b

下面代码找出所有名字中包含”t”的标签:

for tag in soup.find_all(re.compile("t")):
  print(tag.name)
# html
# title

3.列表

如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有标签和标签:

soup.find_all(["a", "b"])
# [<b>The Dormouse's story</b>,
# <a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]

4.方法(自定义函数,传入find_all)

如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数 [4] ,如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False
下面方法校验了当前元素,如果包含 class 属性却不包含 id 属性,那么将返回 True:

def has_class_but_no_id(tag):
  return tag.has_attr('class') and not tag.has_attr('id')```

返回结果中只有

标签没有标签,因为标签还定义了”id”,没有返回和,因为和中没有定义”class”属性.
下面代码找到所有被文字包含的节点内容:

from bs4 import NavigableString
def surrounded_by_strings(tag):
  return (isinstance(tag.next_element, NavigableString)
      and isinstance(tag.previous_element, NavigableString))

for tag in soup.find_all(surrounded_by_strings):
  print tag.name
# p
# a
# a
# a
# p

5.按照CSS搜索

按照CSS类名搜索tag的功能非常实用,但标识CSS类名的关键字 class 在Python中是保留字,使用 class 做参数会导致语法错误.从Beautiful Soup的4.1.1版本开始,可以通过 class_ 参数搜索有指定CSS类名的tag:

soup.find_all("a", class_="sister")
# [<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]

或者:

soup.find_all("a", attrs={"class": "sister"})
# [<a class="sister" href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link1">Elsie</a>,
# <a class="sister" href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link2">Lacie</a>,
# <a class="sister" href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="link3">Tillie</a>]

6.按照text参数查找

通过 text 参数可以搜搜文档中的字符串内容.与 name 参数的可选值一样, text 参数接受 字符串 , 正则表达式 , 列表, True . 看例子:

soup.find_all(text="Elsie")
# [u'Elsie']

soup.find_all(text=["Tillie", "Elsie", "Lacie"])
# [u'Elsie', u'Lacie', u'Tillie']

soup.find_all(text=re.compile("Dormouse"))
[u"The Dormouse's story", u"The Dormouse's story"]

def is_the_only_string_within_a_tag(s):
  ""Return True if this string is the only child of its parent tag.""
  return (s == s.parent.string)

soup.find_all(text=is_the_only_string_within_a_tag)
# [u"The Dormouse's story", u"The Dormouse's story", u'Elsie', u'Lacie', u'Tillie', u'...']

虽然 text 参数用于搜索字符串,还可以与其它参数混合使用来过滤tag.Beautiful Soup会找到 .string 方法与 text 参数值相符的tag.下面代码用来搜索内容里面包含“Elsie”的标签:

soup.find_all("a", text="Elsie")
# [<a href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link1">Elsie</a>]

7.只查找当前标签的子节点

调用tag的 find_all() 方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False .

一段简单的文档:

<html>
 <head>
 <title>
  The Dormouse's story
 </title>
 </head>
...

是否使用 recursive 参数的搜索结果:

soup.html.find_all("title")
# [<title>The Dormouse's story</title>]

soup.html.find_all("title", recursive=False)
# []

到此这篇关于详解BeautifulSoup获取特定标签下内容的方法的文章就介绍到这了,更多相关BeautifulSoup获取特定标签内容内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Selenium+BeautifulSoup+json获取Script标签内的json数据

    Selenium爬虫遇到 数据是以 JSON 字符串的形式包裹在 Script 标签中, 假设Script标签下代码如下: <script id="DATA_INFO" type="application/json" > { "user": { "isLogin": true, "userInfo": { "id": 123456, "nickname":

  • python3 BeautifulSoup模块使用字典的方法抓取a标签内的数据示例

    本文实例讲述了python3 BeautifulSoup模块使用字典的方法抓取a标签内的数据.分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #python 2.7 #XiaoDeng #http://tieba.baidu.com/p/2460150866 #标签操作 from bs4 import BeautifulSoup import urllib.request import re #如果是网址,可以用这个办法来读取网页 #html_doc = "htt

  • python 3利用BeautifulSoup抓取div标签的方法示例

    前言 本文主要介绍的是关于python 3用BeautifulSoup抓取div标签的方法示例,分享出来供大家参考学习,下面来看看详细的介绍: 示例代码: # -*- coding:utf-8 -*- #python 2.7 #XiaoDeng #http://tieba.baidu.com/p/2460150866 #标签操作 from bs4 import BeautifulSoup import urllib.request import re #如果是网址,可以用这个办法来读取网页 #h

  • Python爬虫库BeautifulSoup获取对象(标签)名,属性,内容,注释

    一.Tag(标签)对象 1.Tag对象与XML或HTML原生文档中的tag相同. from bs4 import BeautifulSoup soup = BeautifulSoup('<b class="boldest">Extremely bold</b>','lxml') tag = soup.b type(tag) bs4.element.Tag 2.Tag的Name属性 每个tag都有自己的名字,通过.name来获取 tag.name 'b' tag.

  • 使用Python爬虫库BeautifulSoup遍历文档树并对标签进行操作详解

    下面就是使用Python爬虫库BeautifulSoup对文档树进行遍历并对标签进行操作的实例,都是最基础的内容 html_doc = """ <html><head><title>The Dormouse's story</title></head> <p class="title"><b>The Dormouse's story</b></p>

  • 详解BeautifulSoup获取特定标签下内容的方法

    以下是个人在学习beautifulSoup过程中的一些总结,目前我在使用爬虫数据时使用的方法的是:先用find_all()找出需要内容所在的标签,如果所需内容一个find_all()不能满足,那就用两个或者多个.接下来遍历find_all的结果,用get_txt().get('href').得到文本或者链接,然后放入各自的列表中.这样做有一个缺点就是txt的数据是一个单独的列表,链接的数据也是一个单独的列表,一方面不能体现这些数据之间的结构性,另一方面当想要获得更多的内容时,就要创建更多的空列表

  • 详解C#获取特定进程CPU和内存使用率

    首先是获取特定进程对象,可以使用Process.GetProcesses()方法来获取系统中运行的所有进程,或者使用Process.GetCurrentProcess()方法来获取当前程序所对应的进程对象.当有了进程对象后,可以通过进程对象名称来创建PerformanceCounter类型对象,通过设定PerformanceCounter构造函数的参数实现获取特定进程的CPU和内存使用情况. 具体实例代码如下: 首先是获取本机中所有进程对象,分别输出某一时刻各个进程的内存使用情况: using

  • 详解grep获取MySQL错误日志信息的方法

    为方便维护MySQL,写了个脚本用以提供收集错误信息的接口.这些错误信息来自与MySQL错误日志,而 通过grep mysql可以获取error-log的路径. 以下是全部相关代码: #!/usr/bin/env python2.7 #-*- encoding: utf-8 -*- """ 该模块用于提取每天mysql日志中的异常或错误信息 author: xiaomo email: moxiaomomo@gmail.com """ import

  • 对Xpath 获取子标签下所有文本的方法详解

    在爬虫中遇见这种怎么办 想提取名称, 但是 名称不在一个标签里 使用xpath string()方法 例如 data.xpath("string(path)") path -- 你xpath提取的路径 这里提取到父标签 string() 方法会提取子标签多有的文本内容. 以上这篇对Xpath 获取子标签下所有文本的方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • 详解Spring获取配置的三种方式

    目录 前言 Spring中获取配置的三种方式 通过@Value动态获取单个配置 通过@ConfigurationProperties+前缀方式批量获取 通过Environment动态获取单个配置 总结 前言 最近在写框架时遇到需要根据特定配置(可能不存在)加载 bean 的需求,所以就学习了下 Spring 中如何获取配置的几种方式. Spring 中获取配置的三种方式 通过 @Value 方式动态获取单个配置 通过 @ConfigurationProperties + 前缀方式批量获取配置 通

  • 详解如何获取C#类中发生数据变化的属性信息

    一.前言# 在平时的开发中,当用户修改数据时,一直没有很好的办法来记录具体修改了那些信息,只能暂时采用将类序列化成 json 字符串,然后全塞入到日志中的方式,此时如果我们想要知道用户具体改变了哪几个字段的值的话就很困难了.因此,趁着这个假期,就来解决这个一直遗留的小问题,本篇文章记录了我目前实现的方法,如果你有不同于文中所列出的方案的话,欢迎指出. 代码仓储地址:https://github.com/Lanesra712/ingos-common/tree/master/sample/csha

  • 详解angularjs获取元素以及angular.element()用法

    本文介绍了详解angularjs获取元素以及angular.element()用法 ,分享给大家,具体如下: addClass()-为每个匹配的元素添加指定的样式类名 after()-在匹配元素集合中的每个元素后面插入参数所指定的内容,作为其兄弟节点 append()-在每个匹配元素里面的末尾处插入参数内容 attr() - 获取匹配的元素集合中的第一个元素的属性的值 bind() - 为一个元素绑定一个事件处理程序 children() - 获得匹配元素集合中每个元素的子元素,选择器选择性筛选

  • 用xpath获取指定标签下的所有text的实例

    今天用xpath获取的元素下面text 是被几个b标签分割开的,我想要一次性全部获取,参考了其他人的博客是如下的做法: value_ls = html.xpath("//tr/td[7]") value = value_ls[0].xpath('string(.)').extract()[0] 但是因为我用的是 lxml, 系统报错,lxml元素没有extract() 这个方法,去掉这个方法后,可以正常使用.所以要根据自己的情况选择要不要用.extract() value_ls = h

  • 详解Linux获取线程的PID(TID、LWP)的几种方式

    在 Linux C/C++ 中通常是通过 pthread 库进行线程级别的操作. 在 pthread 库中有函数: pthread_t pthread_self(void); 它返回一个 pthread_t 类型的变量,指代的是调用 pthread_self 函数的线程的 "ID". 怎么理解这个"ID"呢? 这个"ID"是 pthread 库给每个线程定义的进程内唯一标识,是 pthread 库维持的. 由于每个进程有自己独立的内存空间,故此&

  • 详解pandas获取Dataframe元素值的几种方法

    可以通过遍历的方法: pandas按行按列遍历Dataframe的几种方式:https://www.jb51.net/article/172623.htm 选择列 使用类字典属性,返回的是Series类型 data['w'] 遍历Series for index in data['w'] .index: time_dis = data['w'] .get(index) pandas.DataFrame.at 根据行索引和列名,获取一个元素的值 >>> df = pd.DataFrame(

随机推荐