python网络爬虫(5)BeautifulSoup的使用示范

创建并显示原始内容

其中的lxml第三方解释器加快解析速度

import bs4
from bs4 import BeautifulSoup
html_str = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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="link1"><!-- 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>
"""
soup = BeautifulSoup(html_str,'lxml')
print(soup.prettify())

控制台显示出soup需要处理的内容:

 

提取对象内容和属性

搜索包括了所有的标签。默认提取第一个符合条件的标签。

提取Tag对象

其中,name用于显示标签名,去掉name则内容直接显示。

print(soup.name)
print(soup.title.name)
print(soup.title)
print(soup.a)

控制台输出效果如下:

显示属性

attrs用于显示属性。class用于显示选中的标签Tag中的类名。

print(soup.p['class'])
print(soup.p.attrs)

输出结果:

内容文字

显示标记中的文字,NavigableString类型

print(soup.p.string)
print(type(soup.p.string))

效果:

显示注释

显示注释内容,注意与普通string的区别在于最后的类,用于数据分类

print(soup.a.string)
print(type(soup.a.string))

 

文档相关结点

直接子节点数组

结点中的contents输出直接子节点数组,可以通过for逐个输出,通过string属性直接输出内容

print(soup.body.contents)

输出body标签下的直接子节点:

结点children输出直接子节点,和contents类似。不一样的是返回了生成器,一点参考:https://www.cnblogs.com/wj-1314/p/8490822.html

for i in soup.body.children:print(i,end='')

添加了end=''用于去掉print的自动换行

子、孙节点

结点descendants可以输出子节点和孙节点

for i in soup.body.descendants:print(i)

效果:

节点strings输出全部子节点内容值

print(soup.strings)
print('------------------------') for text in soup.strings:print(text,end='')

效果:

节点stripped_strings输出全部内容并去掉回车和空格

for text in soup.stripped_strings:print(text)

print每次输出加上换行后,效果:

父节点相关

父节点parent

print(soup.title)
print(soup.title.parent)

效果:

父辈节点parents,这里只输出名字就好了,否则内容过多

for i in soup.a.parents:print(i.name)

效果:

兄弟节点等

兄弟节点next_sibling,previous_sibling,另有 :next_siblings,previous_siblings

print(soup.p.next_sibling.next_sibling)
print(soup.p.previous_sibling)

效果:

前后节点:next_element,next_elements等......

 

BeautifulSoup的搜索方法

包括了find_all,find,find_parents等等,这里只举例find_all。

find_all中参数name查找名称标记

查找所有b标签

print(soup.find_all('b'))

输出:

查找所有b开头的标签

配合正则表达式使用

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

输出:

查找a开头和b开头的标签

print(soup.find_all(["a", "b"]))

输出:(一个数组,过长)

查找所有标签,True可以匹配任何值

for tag in soup.find_all(True):print(tag.name)

输出:

自定义过滤

查找含有class和id属性的Tag标签

def hasClass_Id(tag):return tag.has_attr('class') and tag.has_attr('id')
print(soup.find_all(hasClass_Id))

效果:

查找关键词参数kwargs并输出

查找id参数为link2的标签

print(soup.find_all(id='link2'))

输出:

查找链接中含有elsie的标签

配合正则表达式

print(soup.find_all(href=re.compile("elsie")))

输出:

查找所有有id属性的标签

print(soup.find_all(id=True))

输出:

查找所有a标签且class内容为sister

print(soup.find_all("a", class_="sister"))

输出:

查找所有链接含有elsie的标签,id为link1

print(soup.find_all(href=re.compile("elsie"), id='link1'))

输出:

不能表达的属性的解决方案

在html5中有些属性不被支持,查找时,通过定义字典实现输出

data_soup = BeautifulSoup('<div data-foo="value">foo!</div>','lxml')
print(data_soup.find_all(attrs={"data-foo": "value"}))

输出:

通过text参数查找文本内容并过滤

 输入:

print(soup.find_all(text=["Tillie", "Elsie", "Lacie"]))
print(soup.find_all(text=re.compile("Dormouse")))

输出:

通过limit参数限制查找数量

输入:

print(soup.find_all("a", limit=2))

输出只有两个:

通过recursive参数只查找直接子节点

soup位于根处

print(soup.find_all("title"))
print(soup.find_all("title", recursive=False))

输出:

使用CSS选择器查找

#直接查找title标签
print soup.select("title")
#逐层查找title标签
print soup.select("html head title")
#查找直接子节点
#查找head下的title标签
print soup.select("head > title")
#查找p下的id="link1"的标签
print soup.select("p > #link1")
#查找兄弟节点
#查找id="link1"之后class=sisiter的所有兄弟标签
print soup.select("#link1 ~ .sister")
#查找紧跟着id="link1"之后class=sisiter的子标签
print soup.select("#link1 + .sister")print soup.select(".sister")
print soup.select("[class~=sister]")print soup.select("#link1")
print soup.select("a#link2")print soup.select('a[href]')print soup.select('a[href="http://example.com/elsie"]')
print soup.select('a[href^="http://example.com/"]')
print soup.select('a[href$="tillie"]')
print soup.select('a[href*=".com/el"]')

 输出:

 

转载于:https://www.cnblogs.com/bai2018/p/10964702.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/393430.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Mingw编译DLib

Mingw编译DLib 因为机器上安装了qt-opensource-windows-x86-mingw530-5.8.0&#xff0c;所以准备使用其自带的mingw530来编译DLib使用。 因为DLib使用CMake的构建脚本&#xff0c;所以还请先安装好CMake。 cmake的下载地址如下https://cmake.org/files/v3.7/cmake-3.7.2-win64-…

探索JavaScript的关闭功能

Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority!“发现功能JavaScript”被BookAuthority评为最佳新功能编程书籍之一 &#xff01; A closure is an inner function that has access to the outer scope, even…

QueryList 配置curl参数 的文档位置 QueryList抓取https 终于找到了

需要设置ssl证书&#xff0c;或者不验证证书&#xff0c;例&#xff1a;$ql QueryList::get(https://...,[],[verify > false]);设置这个 verify > false , 所以curl的其他参数就在这里配置即可 文档在 https://guzzle-cn.readthedocs.io/zh_CN/latest/request-optio…

leetcode981. 基于时间的键值存储(treemap)

创建一个基于时间的键值存储类 TimeMap&#xff0c;它支持下面两个操作&#xff1a; set(string key, string value, int timestamp) 存储键 key、值 value&#xff0c;以及给定的时间戳 timestamp。 2. get(string key, int timestamp) 返回先前调用 set(key, value, times…

物联网笔记

转载于:https://www.cnblogs.com/16-C-kai/p/6596682.html

关于大学生玩网络游戏的调查问卷

1.创建问卷&#xff0c;输入调查名称 2编辑问卷 3检查问卷&#xff0c;是否有误 4.提交并发布问卷 5分享问卷 6.问卷分析 转载于:https://www.cnblogs.com/dzw1996/p/7786754.html

java自动排序_java ArrayList自动排序算法的实现

前几天写的那个是错误的&#xff0c;在这里将正确的更新。。。通过实现ComParator接口&#xff0c;并且对Compare函数进行重写&#xff0c;自定义排序规则实现对ArrayList中对象的排序。。Student类定义&#xff1a;通过右键-》source-》自动生成Set和get方法package first;imp…

1到100的二进制编码_每天经过100天的编码后,我学到了什么

1到100的二进制编码Eleftheria Batsou is a web developer from Thessaloniki, Greece. She gave a talk at the Codegarden conference about her experience doing a solid 100 days of coding every day as part of the #100DaysOfCode Challenge.Eleftheria Batsou是来自希…

第六次 实验

转载于:https://www.cnblogs.com/P201821440005/p/10967987.html

leetcode658. 找到 K 个最接近的元素(二分法)

给定一个排序好的数组&#xff0c;两个整数 k 和 x&#xff0c;从数组中找到最靠近 x&#xff08;两数之差最小&#xff09;的 k 个数。返回的结果必须要是按升序排好的。如果有两个数与 x 的差值一样&#xff0c;优先选择数值较小的那个数。 示例 1: 输入: [1,2,3,4,5], k4,…

du命令、df命令用法

一、du命令 [plain] view plaincopy print?[rootwc1 mysql]# du --help Usage: du [OPTION]... [FILE]... or: du [OPTION]... --files0-fromF Summarize disk usage of each FILE, recursively for directories. Mandatory arguments to long options are mandatory…

mysql 循环创建列_mysql – 查询列中的循环值

我需要创建一个查询,一次只将一列的值移动一行↑&#xff1a;----------------------------| anotherCOL | values_to_loop |----------------------------| 1 | 1 || 2 | 2 || 3 | 3 || 4 | 4 || 5 | 5 || 6 | 6 || 7 | 7 || 8 | 8 || 9 | 9 || 10 | 10 |--------------------…

因子个数与因子和

题目&#xff1a;LightOJ:1341 - Aladdin and the Flying Carpet(因子个数&#xff09; Its said that Aladdin had to solve seven mysteries before getting the Magical Lamp which summons a powerful Genie. Here we are concerned about the first mystery. Aladdin was …

如何在JavaScript中直观地设计状态

by Shawn McKay肖恩麦凯(Shawn McKay) 如何在JavaScript中直观地设计状态 (How to visually design state in JavaScript) 使用状态机和状态图开发应用程序的路线图 (A roadmap for developing applications with state machines & statecharts) Why does state managemen…

SQL Server 2008 - Cannot set a credential for principal 'sa'.

很久没有用到SQL Server了&#xff0c;今天有幸在帮同事解决一个SQL Server数据连接的问题时突然发现我无法修改我的sa用户的密码了。过程是这样的&#xff1a;一开始我本地的数据库实例是Windows认证方式&#xff0c;我想将它改成Windows和数据库混合认证方式后用sa账户登录&a…

leetcode50. Pow(x, n)(快速幂)

实现 pow(x, n) &#xff0c;即计算 x 的 n 次幂函数。 示例 1: 输入: 2.00000, 10 输出: 1024.00000 代码 class Solution {public double myPow(double x, int n) {long tn;return t>0?Pow(x,t):1/Pow(x,-t);//判断幂指数}public double Pow(double x, long n) {if(n…

Java DES 加解密(DES/CBC/PKCS5Padding)

/*** DES加密** param data 加密数据* param key 密钥* return 返回加密后的数据*/public static byte[] desEncrypt(byte[] data, String key, String charset) {try {Cipher cipher Cipher.getInstance("DES/CBC/PKCS5Padding");byte[] k charset null || char…

mysql 连接池 100_mysql的最大连接数默认是100_MySQL

mysql的最大连接数默认是100, 这个数值对于并发连接很多的数据库应用是远远不够的&#xff0c;可以把它适当调大&#xff0c;mysql的最大连接数默认是100, 这个数值对于并发连接很多的数据库应用是远远不够的&#xff0c;可以把它适当调大&#xff0c;whereis safe_mysqld找到s…

angular上传图片_如何使用Angular轻松上传图片

angular上传图片by Filip Jerga由Filip Jerga 如何使用Angular轻松上传图片 (How to make image upload easy with Angular) This is the second part of the tutorial on how to upload an image to Amazon S3. You can find the first part here. In this article, we will …

Java小知识-----Map 按Key排序和按Value排序

Map排序的方式有很多种&#xff0c;这里记录下自己总结的两种比较常用的方式&#xff1a;按键排序(sort by key)&#xff0c; 按值排序(sort by value)。 1、按键排序 jdk内置的java.util包下的TreeMap<K,V>既可满足此类需求&#xff0c;向其构造方法 TreeMap(Comparator…