Python3.x:bs4解析html基础用法

代码:

import urllib.request
from bs4 import BeautifulSoup
import re url = r'http://fund.eastmoney.com/340007.html?spm=search'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
req = urllib.request.Request(url=url, headers=headers)
res = urllib.request.urlopen(req)
html = res.read().decode('utf-8') #使用自带的html.parser解析,速度慢但通用
soup = BeautifulSoup(html, "html.parser")
#或者soup = BeautifulSoup(html, "html5lib")
#输出第一个 title 标签
print(soup.title)
#输出第一个 title 标签的标签名称
print(soup.title.name)
#输出第一个 title 标签的包含内容
print(soup.title.string)
#输出第一个 title 标签的父标签的标签名称
print(soup.title.parent.name)
#输出第一个  p 标签
print(soup.p)
#输出第一个 p 标签的 class 属性内容
print(soup.p['class'])
#输出第一个 a 标签的 href 属性内容
print(soup.a['href'])
#输出第一个  p 标签的所有子节点
print(soup.p.contents)
#输出第一个  a 标签
print(soup.a)
#输出所有的 a 标签,以列表形式显示
print(soup.find_all('a'))
#输出第一个 id 属性等于  gz_gszze 的标签
print(soup.find(id='gz_gszze'))
#输出第一个 id 属性等于 gz_gszze 的标签的文本内容
print(soup.find(id='gz_gszze').get_text())
#获取所有文字内容
print(soup.get_text())
#输出第一个 a 标签的所有属性信息
print(soup.a.attrs)
#循环a标签
for link in soup.find_all('a'):
#获取 link 的 href 属性内容
print(link.get('href')) #对soup.p的子节点进行循环输出
for child in soup.p.children:
print(child) #正则匹配,标签名字中带有sp的标签
for tag in soup.find_all(re.compile("sp")):
print(tag.name)
#按照CSS类名搜索tag的功能非常实用,但标识CSS类名的关键字 class 在Python中是保留字,使用 class 做参数会导致语法错误.从Beautiful Soup的4.1.1版本开始,可以通过 class_ 参数搜索有指定CSS类名的tag
#查找dl标签class为dataItem02的所有dl标签
for tag in soup.find_all("dl", class_="dataItem02"):
print(tag.name)
#或者
for tag in soup.find_all('dl', attrs={'class': "dataItem02"}):
print(tag.name)
#查找dl标签class为包含'ui-font-'字符的所有dl标签
for tagspan in child.find_all("span", class_=re.compile('ui-font-')):
print(tagspan.get_text())
#数组对象定义(用于存放对象)
content_list = []
#按照CSS类名搜索tag的功能非常实用,但标识CSS类名的关键字 class 在Python中是保留字,使用 class 做参数会导致语法错误.从Beautiful Soup的4.1.1版本开始,可以通过 class_ 参数搜索有指定CSS类名的tag
#查找dl标签class为dataItem02的所有dl标签
for tag in soup.find_all("dl", class_="dataItem02"):
#对tag的子节点进行循环输出
for child in tag.children:
print(child)
#将对象存进数组
content_list.append(child)
#获取数组中的第一个对象的值
print('content_list[0]:'+content_list[0].get_text())

find与find_all一起用:

    #第一个class = 'postlist'的div里的所有a 标签是我们要找的信息
#注意:BeautifulSoup()返回的类型是<class 'bs4.BeautifulSoup'>
#   find()返回的类型是<class 'bs4.element.Tag'>
#   find_all()返回的类型是<class 'bs4.element.ResultSet'>
#   <class 'bs4.element.ResultSet'>不能再进项find/find_all操作
all_a = soup.find('div', class_='postlist').find_all('a', target='_blank')
for a in all_a:
title = a.get_text() # 提取文本
if(title != ''):
print("标题:" + title)
#最大页数在span标签中的第10个
pic_max = soup.find_all('span')[10].text #找标题
title = soup.find('h2',class_='main-title').text
#图片地址在img标签alt属性为'图书'地方
pic_url = mess.find('img',alt = '图书')
#获取pic_url中的src属性值:pic_url['src']
html = requests.get(pic_url['src'],headers = headers)
#图片不是文本文件,以二进制格式写入,所以是html.content
#open(路径+文件名,读写模式)
#读写模式:r只读,r+读写,w新建(会覆盖原有文件),a追加,b二进制文件.常用模式
f = open(file_name,'wb')
f.write(html.content)
f.close()
#正则 re.findall  的简单用法(返回string中所有与pattern相匹配的全部字串,返回形式为数组),用法:findall(pattern, string, flags=0)
#示例1:查找全部r标识代表后面是正则的语句
str_1 = re.findall(r"com","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_1)
#输出结果:['com'] #示例2:符号^表示匹配以http开头的的字符串返回,
str_2 = re.findall(r"^http","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_2)
# 输出结果:['http'] #示例3:用$符号表示以html结尾的字符串返回,判断是否字符串结束的字符串
str_3 = re.findall(r"html$","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_3)
# 输出结果:['html'] # 示例4:[...]匹配括号中的其中一个字符
str_4 = re.findall(r"[n,w]b","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_4)
# 输出结果:['nb'] # 示例5:“d”是正则语法规则用来匹配0到9之间的数返回列表
str_5 = re.findall(r"\d","http://www.cnblogs.com/lizm166/p/8143231.html")
str_6 = re.findall(r"\d\d\d","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_5)
# 输出结果:['1', '6', '6', '8', '1', '4', '3', '2', '3', '1']
print (str_6)
# 输出结果:['166', '814', '323'] # 示例6:小d表示取数字0-9,大D表示不要数字,也就是除了数字以外的内容返回
str_7 = re.findall(r"\D","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_7)
# 输出结果:['h', 't', 't', 'p', ':', '/', '/', 'w', 'w', 'w', '.', 'c', 'n', 'b', 'l', 'o', 'g', 's', '.', 'c', 'o', 'm', '/', 'l', 'i', 'z', 'm', '/', 'p', '/', '.', 'h', 't', 'm', 'l'] # 示例7:“w”在正则里面代表匹配从小写a到z,大写A到Z,数字0到9
str_8 = re.findall(r"\w","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_8)
# 输出结果:['h', 't', 't', 'p', 'w', 'w', 'w', 'c', 'n', 'b', 'l', 'o', 'g', 's', 'c', 'o', 'm', 'l', 'i', 'z', 'm', '1', '6', '6', 'p', '8', '1', '4', '3', '2', '3', '1', 'h', 't', 'm', 'l'] # 示例8:“W”在正则里面代表匹配除了字母与数字以外的特殊符号
str_9 = re.findall(r"\W","http://www.cnblogs.com/lizm166/p/8143231.html")
print (str_9)
# 输出结果:[':', '/', '/', '.', '.', '/', '/', '/', '.']
# 获取所有a标签(属性target为_blank)
tr.find_all('a',target='_blank')

作者:整合侠
链接:http://www.cnblogs.com/lizm166/p/8205085.html
来源:博客园
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Python3.x:bs4解析html基础用法的更多相关文章

  1. bs4.BeautifulSoup的基础用法

    导入模块 from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc,"html.parser") 下面看下常见的用法 ...

  2. bs4 解析 以及用法

    bs4解析 bs4: 环境安装: lxml bs4 bs4编码流程: 1.实例化一个bs4对象,且将页面源码数据加载到该对象中 2.bs相关的方法或者属性实现标签定位 3.取文本或者取属性 bs的属性 ...

  3. logstash安装与基础用法

    若是搭建elk,建议先安装好elasticsearch 来自官网,版本为2.3 wget -c https://download.elastic.co/logstash/logstash/packag ...

  4. Smarty基础用法

    一.Smarty基础用法: 1.基础用法如下 include './smarty/Smarty.class.php';//引入smarty类 $smarty = new Smarty();//实例化s ...

  5. asyncio 基础用法

    asyncio 基础用法 python也是在python 3.4中引入了协程的概念.也通过这次整理更加深刻理解这个模块的使用 asyncio 是干什么的? asyncio是Python 3.4版本引入 ...

  6. 【Python爬虫】selenium基础用法

    selenium 基础用法 阅读目录 初识selenium 基本使用 查找元素 元素互交操作 执行JavaScript 获取元素信息 等待 前进后退 Cookies 选项卡管理 异常处理 初识sele ...

  7. 爬虫的三种解析方式(正则解析, xpath解析, bs4解析)

    一 : 正则解析 : 常用正则回顾: 单字符: . : 除换行符以外的所有字符 [] : [aoe] [a-w] 匹配集合中任意一个字符 \d : 数字 [0-9] \D : 非数字 \w : 非数字 ...

  8. python bs4解析网页时 bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to inst(转)

    Python小白,学习时候用到bs4解析网站,报错 bs4.FeatureNotFound: Couldn't find a tree builder with the features you re ...

  9. 爬虫简介、requests 基础用法、urlretrieve()

    1. 爬虫简介 2. requests 基础用法 3. urlretrieve() 1. 爬虫简介 爬虫的定义 网络爬虫(又被称为网页蜘蛛.网络机器人),是一种按照一定的规则,自动地抓取万维网信息的程 ...

随机推荐

  1. jdbc链接数据库,获取表名,字段名和数据

    import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import  ...

  2. HTTP/2笔记之流和多路复用

    零.前言 本部分将讲解HTTP/2协议中对流的定义和使用,其实就是在说HTTP/2是若何做到多路复用的. 一.流和多路复用的关系 1. 流的概念 流(Stream),服务器和客户端在HTTP/2连接内 ...

  3. MongoDB复制集原理

    版权声明:本文由孔德雨原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/136 来源:腾云阁 https://www.qclo ...

  4. Android 简单案例:可移动的View

    CrossCompatibility.rar 1. VersionedGestureDetector.java import android.content.Context; import andro ...

  5. navigater导航

    1.css的hover事件2.url事件(或者click事件),激活当前项3.第一导航与第二导航的移入移出事件(可以通过left,top值来显示,也可以变化宽度,高宽来显示)4.有二级导航的另外给cl ...

  6. JAVA学习基础知识总结(原创)

    (未经博主允许,禁止转载!) 一.基础知识:1.JVM.JRE和JDK的区别: JVM(Java Virtual Machine):java虚拟机,用于保证java的跨平台的特性. java语言是跨平 ...

  7. 04Add.ashx(新增班级)

    04Add.html <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <hea ...

  8. MySQL逗号分割字段的列转行

    前言: 由于很多业务表因为历史原因或者性能原因,都使用了违反第一范式的设计模式.即同一个列中存储了多个属性值(具体结构见下表). 这种模式下,应用常常需要将这个列依据分隔符进行分割,并得到列转行的结果 ...

  9. s3对象存储

    bkstorages 模块帮助你在蓝鲸应用中使用多种文件存储服务作为后端,用于加速静态资源,管理用户上传文件. 自定静态文件 storage 如果通过修改配置文件满足不了你的需求,你随时可以通过继承 ...

  10. python 类 __call__

    __call__ 对象后面加括号,触发执行. 即:对象() 或者 类()() class dog(object): def __init__(self,name): self.name = name ...