#beautifulsoup库的安装
pip install beautifulsoup4
python -m pip install --upgrage pip
from bs4 import BeautifulSoup #----------------beautifulsoup库的使用--------------------------------------
import requests
from bs4 import BeautifulSoup
url = "http://python123.io/ws/demo.html"
r = requests.get(url)
# print(r.text)
demo = r.text
soup = BeautifulSoup(demo,"html.parser") #熬一锅`粥
#print(soup.prettify()) #打印这锅粥 #下行遍历函数:.contents() .children()用于循环 .descendants()
soup.head #获取head标签
soup.head.contents #获取head的子节点,返回类型是列表
soup.body.contents #
len(soup.body.contents) #terurn 5
soup.body.contents[2]
print('以下输出子节点:')
for child in soup.body.children:
print('##',child)
print('以下输出子孙节点:')
for child in soup.body.descendants:
print('**',child) #---上行遍历 .parent .parents(用于循环)
soup.title.parent #return <head><title>This is a python demo page</title></head>
soup.html.parents #返回 html所有内容
soup.parent #返回为空
print('以下输出父节点:')
for par in soup.a.parents:
if par is None:
print('$$$',par)
else:
print('%',par.name) #----平行遍历----
# 向后.next_sibling 向前.previous_sibling 加 s 用于遍历
#title 与 p标签 不构成平行关系
soup.a.next_sibling #return ' and ' 所以<a>标签的下一个标签不一定是<a>标签,需要判断
soup.a.next_sibling.next_sibling #return <a ...</a> soup.a.previous_sibling
soup.a.previous_sibling.previous_sibling
print('以下输出下行遍历:')
for sibling in soup.a.next_siblings:
print('##',sibling)
print('以下输出上行遍历:')
for sibling in soup.a.previous_siblings:
print('**',sibling)

最新文章

  1. Leetcode 笔记 36 - Sudoku Solver
  2. JavaScript 精粹
  3. 简单轮播js实现
  4. clover 在win10下工作不正常
  5. PaintView 绘图控件解析
  6. LDA 初见(JGibbLDA-v.1.0 eclipse使用)
  7. linux 不能用clock 计算sleep的时间
  8. localhost访问不了
  9. [系统开发] FileMaker进销存系统
  10. Git_Windows 系统下Git安装图解
  11. 虚拟机Linux下找不到/dev/cdrom
  12. Session与Cookie间不得不说的一些事
  13. MongoDB--架构搭建(主从、副本集)之主从
  14. Ionic3学习笔记(一)安装、项目结构与常用命令
  15. 删除a表中和b表相同的数据
  16. Hive 任务优化 tips
  17. __getattr__()
  18. Django 学习 (第四部)
  19. pyautogui_pdf内容提取到excel内_3
  20. 廖雪峰Java6IO编程-1IO基础-1IO简介

热门文章

  1. 让SpringBoot的jackson支持JavaBean嵌套的protobuf
  2. Kerberos kinit crontab定时任务不生效的问题解决
  3. java入门到秃路线导航,元芳你怎么看?【教学视频+博客+书籍整理】
  4. Linux进程和线程
  5. js奥义:原型与原型链(2)
  6. Java连接MySQL简单步骤及常见问题解析
  7. 「刷题」xor
  8. NOIP模拟 30
  9. call 与apply深入
  10. java架构之路-(NoSql专题)MongoDB快速上手