python爬虫 - BeautifulSoup(2)子孙节点(.children .descendants)和父节点(.parents)
2018-02-20 19:48
525 查看
3. 1子节点和子孙节点
soup.body.h1# 选中body 标签下的h1,这个h1 标签是body标签的子节点
同理,soup.div.find_all(‘img’)会找到所有div里面的img标签。
.children 和.descendants
对比代码如下:html = urlopen('http://www.pythonscraping.com/pages/page3.html') soup = BeautifulSoup(html, 'lxml') children = soup.find('table',{'id':'giftList'}).children descendants = soup.find('table',{'id':'giftList'}).descendants sum = 0 for child in children: print(child) sum +=1 print(sum) sum2 = 0 for descendant in descendants: sum2+=1 print(descendant) print(sum2)
运行结果可知 sum = 13, sum2 = 86
取descendants的第一部分作比较可以发现
<tr><th>#=============<tr>是soup.find('table',{'id':'giftList'})的子节点==== Item Title </th><th> Description </th><th> Cost </th><th> Image </th></tr>#============<tr>是soup.find('table',{'id':'giftList'})的子节点==== <th> #============<th>是<tr>的子节点,('table',{'id':'giftList'})的子孙节点== Item Title </th> #============<th>是<tr>的子节点,('table',{'id':'giftList'})的子孙节点== Item Title#=========文本是<th>标签的内容,也是子孙节点================ <th>#============同上==================== Description </th> Description <th> Cost </th> Cost ....
对比可知,children只列出了标签所包含的内容。而descendants列出了所有包含的标签节点以及文本,即子标签中的所有子子孙孙标签都会查找返回。
3.2 父节点
通常情况下我们更经常查找子节点,而在某些特定情况下会用到查询父节点,.parents 和 .parent。from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('http://www.pythonscraping.com/pages/warandpeace.html') soup = BeautifulSoup(html) print(soup.find('img', {'src':'../img/gifts/img1.jpg'}).parent.previous_sibling.get_text())
分析一下代码是如何工作的。
<tr> --<td> --<td>(3) --"$15.00"(4) --s<td>(2) --<img src="../img/gifts/img1.jpg">(1)
1.首先定位到含src=”../img/gifts/img1.jpg”的标签img
2.选中img标签的父节点s.
3.选中s的上一个同层级标签
4.选取标签中的文字
相关文章推荐
- Python爬虫包 BeautifulSoup 学习(七) children等应用
- python爬虫之BeautifulSoup
- 17 - 05 - 26 Python contents / children / descendants 区别
- Python 爬虫 —— BeautifulSoup
- python爬虫主要就是五个模块:爬虫启动入口模块,URL管理器存放已经爬虫的URL和待爬虫URL列表,html下载器,html解析器,html输出器 同时可以掌握到urllib2的使用、bs4(BeautifulSoup)页面解析器、re正则表达式、urlparse、python基础知识回顾(set集合操作)等相关内容。
- Python爬虫(十四)_BeautifulSoup4 解析器
- python爬虫日志(7)BeautifulSoup
- Python3.7 爬虫(三)使用 Urllib2 与 BeautifulSoup4 爬取网易云音乐歌单
- Python爬虫包 BeautifulSoup 学习(十) 各种html解析器的比较及使用
- python爬虫之BeautifulSoup
- 【python爬虫】BeautifulSoup库的选择器select()方法
- python爬虫——BeautifulSoup基础操作
- python 爬虫利器优美的BeautifulSoup
- python-爬虫-beautifulsoup
- python结合BeautifulSoup爬虫小实战
- python学习(6):python爬虫之requests和BeautifulSoup的使用
- python爬虫里信息提取的核心方法: Beautifulsoup、Xpath和正则表达式
- Python3 BeautifulSoup爬虫 HDU自动提交
- python爬虫:BeautifulSoup 使用select方法的使用
- 有意思的python爬虫系列(beautifulSoup,urllib,selenium)