1

Python学习笔记005-提取数据:如何从网页中提取兴趣内容

 2 years ago
source link: http://www.mrliangqi.com/1713.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Python学习笔记005-提取数据:如何从网页中提取兴趣内容

Python实战 2022-04-02 0 8

前言: HTML的页面是由很多基本元素组成的,一般叫做标签

<标签名> 网页内容</标签名> <red>这就是红色 </red> <bold>这是加粗</bold>
<center> <red>这就是红色 </red> <bold>这是加粗</bold> </center>

<!–more–>
这就是把红色和加粗的文字居中显示起来.

一.标签的属性
<a href=”wwww.baidu.com” target=”_blank”>点我在新窗口打开百度</a>
标签名/属性名字/属性值
<font size=”12″>这是12号字体</font>
标签的属性有的是特有的,有的是所有标签都有的,比如 font的size. id/class就是所有都有的.
id属性:一般代表标签的名字, id=”header”
class属性:标签的类别,是所有标签都有的样式.
二.HTML基本要素
1.html是由一个标签组成的
2.标签可以嵌套,里面的标签可以有其他标签
3.在标签的开始标记中,可以指定标签的属性
4.id和class属性是最广泛使用的属性
三.使用beautifulsoup提取内容
beautifulsoup是一个python库,用于分析HTML
Mac安装方法:
#conda install bs4
Downloading and Extracting Packages
bs4-4.10.0 | 10 KB | ##################################### | 100%
conda-4.12.0 | 14.5 MB | ##################################### | 100%

fo=open(“aa.html”,”r”,encoding=”utf-8″)
html_content=fo.read()
fo.close()
print(html_content)

find_all:在html文档中查看特定标签名特定属性的标签值

fo=open(“aa.html”,”r”,encoding=”utf-8″) #从本地加载aa.html文件,读权限
html_content=fo.read()
fo.close()
print(html_content)
from bs4 import BeautifulSoup #导入bs4库
doc=BeautifulSoup(html_content)

title_label=doc.title
print(title_label.get.text())

logo_label=doc.find_all(“div”,class_=”logo”)
print(logo_label)

attrs:可以通过标签获取attrs属性
logo_label=doc.find_all(“div”,class_=”logo”)
print(logo_label)
总结:
beautifulsoup的使用,首先需要把html读取到python中,在用存储文件内容变量构造 beaufulsoup对象
可以使用Beautifulsoup对象的find_all方法,找到标签名和属性值都符合条件的标签对象
比如: doc.find_all(“div”,class_=”logo”)代表找到标签名字为div,class属性为logo的标签.
**网页抓取的方法分析:**
认真查看过滤内容所在的特征码,过滤出包含文本的标签.
如果关系比较复杂,可以分部进行,最后过滤出来需要的内容.

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK