博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
爬虫模块BeautifulSoup
阅读量:4503 次
发布时间:2019-06-08

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

中文文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#

1.1      安装BeautifulSoup模块和解析器

1)         安装BeautifulSoup

         pip install beautifulsoup4

2)         安装解析器

         pip install lxml

  pip install html5lib

 

 

 

1.2      对象种类

  • Tag :   标签对象,如:<p class="title"><b>yoyoketang</b></p>,这就是一个标签
  • NavigableString :字符对象,如:这里是我的微信公众号:yoyoketang
  • BeautifulSoup   :就是整个html对象
  • Comment    :注释对象,如:!-- for HTML5 --,它其实就是一个特殊NavigableString

 

1.3      常用方法

# coding:utf-8__author__ = 'Helen''''description:爬虫模块BeautifulSoup学习'''import requestsfrom bs4 import BeautifulSoupr = requests.get("https://www.baidu.com/")soup = BeautifulSoup(r.content,'html5lib')print soup.a	#  根据tab名输出,只输出第一个print soup.find('a')	#	同上print soup.find_all('a')	# 输出所有a元素	# 找出对应的tag,再根据元素属性找内容print soup.find_all('a',{'href':'https://www.hao123.com','name':'tj_trhao123'})# .contents(tag对象contents可以获取所有的子节点,返回的是list,获取该元素的直接子节点)print soup.find('a').contents[0]	# 输出第一个节点print soup.find('div',id='u1').contents[1]	# 输出第二个节点# .children(点children这个生成的是list对象,跟上面的点contents功能一样,但是不能通过下标读,只能for循环读)for i in soup.find('div',id='u1').children:	print i# .descendants(获取所有的子孙节点)for i in soup.find(class_='head_wrapper').descendants:	print i

  

转载于:https://www.cnblogs.com/helenMemery/p/7290974.html

你可能感兴趣的文章
Linux 内核中的 Device Mapper 机制
查看>>
4.分布式搭建
查看>>
pycharm环境下用Python+Django开发web搭建
查看>>
核心显示类
查看>>
T-SQL 筛选删除重复记录并保留一条
查看>>
分析_中国菜刀
查看>>
C# 读取Log4net 日志文件
查看>>
window环境下搭建wordpress
查看>>
多线程模块的同步机制event对象
查看>>
svn
查看>>
idea xml文件未编译报错(持续更新)
查看>>
javascript思维导图
查看>>
程序语言词汇外语收藏
查看>>
PHP中array_merge函数与array+array的区别
查看>>
C# winform及.net 中使用 Server.URLEncode
查看>>
【循序渐进学Python】7.面向对象的核心——类型(上)
查看>>
第四次作业
查看>>
JS变量和数据类型
查看>>
oracle汉字转拼音
查看>>
easyloader [easyui_1.4.2] 分析源码,妙手偶得之
查看>>