栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python爬虫简单笔记之BeautifulSoup4的简单用法

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python爬虫简单笔记之BeautifulSoup4的简单用法

记录一下Python爬虫常用库BeautifulSoup4的简单用法。其中demo均以自己的博客网站为对象。

1 urllib和urllib2

Python中包含了两个网络模块,分别是urllib与urllib2,urllib2是urllib的升级版,拥有更强大的功能。urllib,让我们可以像读文件一样,读取http与ftp。而urllib2,则在urllib的基础上,提供了更多的接口,如cookie、代理、认证等更强大的功能。

这里借鉴下文章一和文章二的说法:

  1. urllib仅可以接受URL,不能创建,设置headers的request类实例;

  2. 但是urllib提供urlencode()方法用来GET查询字符串的产生,而urllib2则没有(这是urllib和urllib2经常一起使用的主要原因)

  3. 编码工作使用urllib的urlencode()函数,帮我们讲key:value这样的键值对转换成‘key=value’这样的字符串,解码工作可以使用urllib的unquote

该两个库都是Python自带库,且由于简单爬虫所需要的功能比较少,所以不做更多赘述。

2 BeautifulSoup

中文文档:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/#id13

现在的Mac已经不能用

$ sudo easy_install pip

来安装pip,而只能用一个get-pip.py的方法,网上有大量教程。然后安装完毕后用pip来安装beautilfulsoup4。

安装完以后一个简单的例子(环境Python2.7,其实Python3在这段代码也差不多):

from urllib import urlopenfrom bs4 import BeautifulSoup
html = urlopen("http://blog.orisonchan.cc")
bsObj = BeautifulSoup(html.read())
print(bsObj.h1)
  • 网页不存在的情况如何判断

方法一:空值判断

if html is None:
    print("URL not found")else:    # expressions

方法二:try-catch

try:
    html = urlopen("http://blog.orisonchan.cc")except HTTPError as e:
    print(e)    # expressions

这里从O`Reilly系列图书《Python网络数据采集》中摘抄一个完整例子:

from urllib.request import urlopenfrom urllib.error import HTTPErrorfrom bs4 import BeautifulSoupdef getTitle(url):
    try:
        html = urlopen(url) 
    except HTTPError as e:        return None
    try:
        bsObj = BeautifulSoup(html. read())
        title = bsObj.body.h1    except AttributeError as e:        return None
    return title


title = getTitle(" http://www.pythonscraping.com/pages/page1.html")if title == None:
    print("Title could not be found")else:
    print(title)
2.1 常用方法2.1.1 find()
  • 格式:

find(name, attributes, recursive, text ,keywords)

  • 参数介绍

name:标签名,如a,p。
attributes:一个标签的若干属性和对应的属性值。
recursive:是否递归。如果是,就会查找tag的所有子孙标签,默认true。
text:标签的文本内容去匹配,而不是标签的属性。
keyword:选择那些具有指定属性的标签。

find()示例:

from urllib import urlopenfrom bs4 import BeautifulSoup
html = urlopen("http://blog.orisonchan.cc")
bsObj = BeautifulSoup(html.read(), 'html.parser')print str(bsObj.find(name='h1', attrs={'class': {'post-title'}}))

结果:

常见“树”概念解析(1)
2.1.2 find_all()

find_all(name, attributes, recursive, text , limit, keywords)

  • 参数介绍

name:标签名,如a,p。
attributes:一个标签的若干属性和对应的属性值。
recursive:是否递归。如果是,就会查找tag的所有子孙标签,默认true。
text:标签的文本内容去匹配,而不是标签的属性。
limit: 个数限制,find其实就等于limit=1,查看find源码即可发现。
keyword:选择那些具有指定属性的标签。

bsObj.find_all("a")可以简写为bsObj("a")

find_all()示例:

from urllib import urlopenfrom bs4 import BeautifulSoup
html = urlopen("http://blog.orisonchan.cc")
bsObj = BeautifulSoup(html.read(), 'html.parser')print str(bsObj.find_all(name='h1', attrs={'class': {'post-title'}})[1:3]).decode('unicode-escape')

结果:

[Spark聚合下推思路以及demo, 写一个Spark DataSource的随手笔记]
2.2 常用对象2.2.1 tag对象

即html中的标签。其中两个属性就是name和attributes。使用如下:

from urllib import urlopenfrom bs4 import BeautifulSoup
html = urlopen("http://blog.orisonchan.cc")
bsObj = BeautifulSoup(html.read(), 'html.parser')
tag = bsObj.h1
print(tag)
print(tag.name)
print(tag.attrs)
print(tag['class'])

结果:

常见“树”概念解析(1)h1
{u'class': [u'post-title'], u'itemprop': u'name headline'}
[u'post-title']
2.2.2 NavigableString对象

用来表示包含在tag中的文字。注意!如果tag中包含子tag,navigableString对象会是None!

2.2.3 Comment对象

用来查找HTML里的注释标签。是一个特殊的NavigableString,所以也有其性质。

2.3 导航树(Navigating Trees)2.3.1 子节点们
  • 对tag级别调用childen属性可得到该tag的所有子节点:

from urllib import urlopenfrom bs4 import BeautifulSoup
html = urlopen("http://blog.orisonchan.cc")
bsObj = BeautifulSoup(html.read(), 'html.parser')for child in bsObj.find(name='h1', attrs={'class': {'post-title'}}).children:
    print(child)

结果:

常见“树”概念解析(1)
2.3.2 兄弟节点(们)
  • next_siblings属性和previous_siblings属性可以查询兄弟节点们。

  • next_sibling和previous_sibling可以查下一个/上一个兄弟。

需要注意的是,很可能直接相邻的上一个下一个兄弟节点并不是Tag而是一个换行符啊标点符号啊等NavigableString对象(字符串节点)。

2.3.3 父节点(们)
  • parent属性得到某元素父节点。

  • parents属性递归得到所有的父节点。

2.4 过滤器2.4.1 字符串

即上文提到bsObj.find_all("a")和bsObj("a")。

2.4.2 标签列表

形如bsObj.find_all(["a", "p"])则会去寻找a标签和p标签。

2.4.3 True

True可以匹配任何职,但是不会返回字符串节点

2.4.4 正则表达式
  • 引入Python自带的re(regular expressions)

示例:

from urllib import urlopenfrom bs4 import BeautifulSoupimport re
html = urlopen("http://blog.orisonchan.cc/2018/08/14/43")
bsObj = BeautifulSoup(html.read(), 'html.parser')print bsObj.find_all(name='img', attrs={'src': re.compile("[a-z]*.png")})[1]

结果:

2.4.5 自定义方法作为参数

这个不知道该怎么表述,有兴趣的可以去官方文档看一下,这里直接来一个demo:

from urllib import urlopenfrom bs4 import BeautifulSoupimport re
html = urlopen("http://blog.orisonchan.cc/2018/08/14/43")
bsObj = BeautifulSoup(html.read(), 'html.parser')def png_image(tag):
    return tag.name == "img" and re.compile("[a-z]*tree.png").search(tag.attrs["src"])for img in bsObj.find_all(png_image):
    print(img)

结果返回了该篇文章4个img中的3个:

         

作者:orisonchan

链接:https://www.jianshu.com/p/95b1bc3b2f73

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/222909.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号