博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 之 BeautifulSoup标签查找与信息提取
阅读量:7121 次
发布时间:2019-06-28

本文共 1520 字,大约阅读时间需要 5 分钟。

一、 查找a标签

(1)查找所有a标签

>>> for x in soup.find_all('a'):    print(x)    ElsieLacieTillie

(2)查找所有a标签,且属性值href中需要保护关键字“”

>>> for x in soup.find_all('a',href = re.compile('lacie')):    print(x)Lacie

(3)查找所有a标签,且字符串内容包含关键字“Elsie”

>>> for x in soup.find_all('a',string = re.compile('Elsie')):    print(x)    Elsie

(4)查找body标签的所有子标签,并循环打印输出

>>> for x in soup.find('body').children:    if isinstance(x,bs4.element.Tag):        #使用isinstance过滤掉空行内容        print(x)        

The Dormouse's story

Once upon a time there were three little sisters; and their names wereElsie,Lacie andTillie;and they lived at the bottom of a well.

二、信息提取(链接提取)

(1)解析信息标签结构,查找所有a标签,并提取每个a标签中href属性的值(即链接),然后存在空列表;

>>> linklist = []>>> for x in soup.find_all('a'):    link = x.get('href')    if link:        linklist.append(link)       >>> for x in linklist:        #验证:环打印出linklist列表中的链接    print(x)  http://example.com/elsiehttp://example.com/laciehttp://example.com/tillie

小结:链接提取 <---> 属性内容提取 <---> x.get('href')
(2)解析信息标签结构,查找所有a标签,且每个a标签中href中包含关键字“elsie”,然后存入空列表中;

>>> linklst = []>>> for x in soup.find_all('a', href = re.compile('elsie')):    link = x.get('href')    if link:        linklst.append(link)    >>> for x in linklst:        #验证:循环打印出linklist列表中的链接    print(x)    http://example.com/elsie

小结:在进行a标签查找时,加入了对属性值href内容的正则匹配内容 <---> href = re.compile('elsie')

(3)解析信息标签结构,查询所有a标签,然后输出所有标签中的“字符串”内容;

>>> for x in soup.find_all('a'):    string = x.get_text()    print(string)   ElsieLacieTillie

 

转载于:https://www.cnblogs.com/my1e3/p/6657926.html

你可能感兴趣的文章
一学就会的django项目服务器部署nginx-uwsgi-django/build
查看>>
ICPR 2018|阿里巴巴读光OCR及MTWI数据集亮相引关注
查看>>
对象存储oss中bucket中存在的文件夹怎么移动或者复制到另一个账号中的对象存储oss中???...
查看>>
RocksDB Write Prepared Policy
查看>>
那些我希望在一开始使用 Zsh(oh-my-zsh) 时就知道的
查看>>
为节省内存,Firefox 将用新方式阻止加载没用到的标签页
查看>>
JDBC学习再小结
查看>>
P3 项目轶事之面试
查看>>
屌炸天,JDK8的排序大法!!
查看>>
android兼容oppo手机刘海屏解决方案
查看>>
html中让input标签只读不可编辑的方法
查看>>
IOS隐藏键盘
查看>>
代码为什么那么乱! 换种方法学面向对象
查看>>
WPF中动态添加控件,并为控制指定样式
查看>>
Aruba:物联网有望在2019年大规模应用
查看>>
区块链应用场景:征信和权属管理
查看>>
CES Asia专题|中国移动发布全球最小通信模组,助力物联网发展
查看>>
【MySql】赶集网mysql开发36条军规
查看>>
服务越好收入越高,300万快递小哥有了终身成长体系
查看>>
ipa-server
查看>>