python 自己写爬虫 ----- BeautifulSoup
2015-07-23 10:22
761 查看
html ----- 获取了 源链接的 htmlsoup = BeautifulSoup( html ) ----- 获得BeautifulSoup对象获得特定标签或有着特定属性的标签:titleTag = soup.html.head.title输出:#<title>理财顾问招聘-信泽联合基金招聘-拉勾网</title>
title_tag = soup.html.head.titleprint title_tag.string#输出:#理财顾问招聘-信泽联合基金招聘-拉勾网ps = soup.findAll( 'p' ) ------ 找到所有的 p标签的内容,返回列表divs = soup.findAll( 'dd' , attrs={'class':'job_bt'} ) ----- 找到 dd 标签 属性class = job_bt 的内容print divs
什么是BeautifulSoup?Beautiful Soup 是用Python写的一个HTML/XML的解析器,它可以很好的处理不规范标记并生成剖析树(parse tree)。 它提供简单又常用的导航(navigating),搜索以及修改剖析树的操作。它可以大大节省你的编程时间。直接看例子:#!/usr/bin/python# -*- coding: utf-8 -*-from bs4 import BeautifulSouphtml_doc = """<html><head><title>The Dormouse's story</title></head><body><p class="title"><b>The Dormouse's story</b></p><p class="story">Once upon a time there were three little sisters; and their names were<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;and they lived at the bottom of a well.</p><p class="story">...</p>"""soup = BeautifulSoup(html_doc)print soup.titleprint soup.title.nameprint soup.title.stringprint soup.pprint soup.aprint soup.find_all('a')print soup.find(id='link3')print soup.get_text()结果为:<title>The Dormouse's story</title>titleThe Dormouse's story<p class="title"><b>The Dormouse's story</b></p><a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>The Dormouse's storyThe Dormouse's storyOnce upon a time there were three little sisters; and their names wereElsie,Lacie andTillie;and they lived at the bottom of a well....可以看出:soup 就是BeautifulSoup处理格式化后的字符串,soup.title 得到的是title标签,soup.p 得到的是文档中的第一个p标签,要想得到所有标签,得用find_all函数。find_all 函数返回的是一个序列,可以对它进行循环,依次得到想到的东西.get_text() 是返回文本,这个对每一个BeautifulSoup处理后的对象得到的标签都是生效的。你可以试试 print soup.p.get_text()其实是可以获得标签的其他属性的,比如我要获得a标签的href属性的值,可以使用 print soup.a['href'],类似的其他属性,比如class也是可以这么得到的(soup.a['class'])。特别的,一些特殊的标签,比如head标签,是可以通过soup.head 得到,其实前面也已经说了。如何获得标签的内容数组?使用contents 属性就可以 比如使用 print soup.head.contents,就获得了head下的所有子孩子,以列表的形式返回结果,可以使用 [num] 的形式获得 ,获得标签,使用.name 就可以。获取标签的孩子,也可以使用children,但是不能print soup.head.children 没有返回列表,返回的是 <listiterator object at 0x108e6d150>,不过使用list可以将其转化为列表。当然可以使用for 语句遍历里面的孩子。关于string属性,如果超过一个标签的话,那么就会返回None,否则就返回具体的字符串print soup.title.string 就返回了 The Dormouse's story超过一个标签的话,可以试用strings向上查找可以用parent函数,如果查找所有的,那么可以使用parents函数查找下一个兄弟使用next_sibling,查找上一个兄弟节点使用previous_sibling,如果是查找所有的,那么在对应的函数后面加s就可以如何遍历树? 使用find_all 函数find_all(name, attrs, recursive, text, limit, **kwargs)举例说明:print soup.find_all('title')print soup.find_all('p','title')print soup.find_all('a')print soup.find_all(id="link2")print soup.find_all(id=True)返回值为:[<title>The Dormouse's story</title>][<p class="title"><b>The Dormouse's story</b></p>][<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>][<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>][<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]通过css查找,直接上例子把:print soup.find_all("a", class_="sister")print soup.select("p.title")通过属性进行查找print soup.find_all("a", attrs={"class": "sister"})通过文本进行查找print soup.find_all(text="Elsie")print soup.find_all(text=["Tillie", "Elsie", "Lacie"])限制结果个数print soup.find_all("a", limit=2)结果为:[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>][<p class="title"><b>The Dormouse's story</b></p>][<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>][u'Elsie'][u'Elsie', u'Lacie', u'Tillie'][<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>][code]
title_tag = soup.html.head.titleprint title_tag.string#输出:#理财顾问招聘-信泽联合基金招聘-拉勾网ps = soup.findAll( 'p' ) ------ 找到所有的 p标签的内容,返回列表divs = soup.findAll( 'dd' , attrs={'class':'job_bt'} ) ----- 找到 dd 标签 属性class = job_bt 的内容print divs
方法以及findAll从给定的点开始遍历整个树,并找到满足给定条件所有[code]Tag
NavigableString。
findall函数原型定义如下:[/code]
findAll(name=None, attrs={}, recursive=True, text=None,limit=None, **kwargs)
find(name,attrs,
recursive,
text,
**kwargs)
什么是BeautifulSoup?Beautiful Soup 是用Python写的一个HTML/XML的解析器,它可以很好的处理不规范标记并生成剖析树(parse tree)。 它提供简单又常用的导航(navigating),搜索以及修改剖析树的操作。它可以大大节省你的编程时间。直接看例子:#!/usr/bin/python# -*- coding: utf-8 -*-from bs4 import BeautifulSouphtml_doc = """<html><head><title>The Dormouse's story</title></head><body><p class="title"><b>The Dormouse's story</b></p><p class="story">Once upon a time there were three little sisters; and their names were<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;and they lived at the bottom of a well.</p><p class="story">...</p>"""soup = BeautifulSoup(html_doc)print soup.titleprint soup.title.nameprint soup.title.stringprint soup.pprint soup.aprint soup.find_all('a')print soup.find(id='link3')print soup.get_text()结果为:<title>The Dormouse's story</title>titleThe Dormouse's story<p class="title"><b>The Dormouse's story</b></p><a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>The Dormouse's storyThe Dormouse's storyOnce upon a time there were three little sisters; and their names wereElsie,Lacie andTillie;and they lived at the bottom of a well....可以看出:soup 就是BeautifulSoup处理格式化后的字符串,soup.title 得到的是title标签,soup.p 得到的是文档中的第一个p标签,要想得到所有标签,得用find_all函数。find_all 函数返回的是一个序列,可以对它进行循环,依次得到想到的东西.get_text() 是返回文本,这个对每一个BeautifulSoup处理后的对象得到的标签都是生效的。你可以试试 print soup.p.get_text()其实是可以获得标签的其他属性的,比如我要获得a标签的href属性的值,可以使用 print soup.a['href'],类似的其他属性,比如class也是可以这么得到的(soup.a['class'])。特别的,一些特殊的标签,比如head标签,是可以通过soup.head 得到,其实前面也已经说了。如何获得标签的内容数组?使用contents 属性就可以 比如使用 print soup.head.contents,就获得了head下的所有子孩子,以列表的形式返回结果,可以使用 [num] 的形式获得 ,获得标签,使用.name 就可以。获取标签的孩子,也可以使用children,但是不能print soup.head.children 没有返回列表,返回的是 <listiterator object at 0x108e6d150>,不过使用list可以将其转化为列表。当然可以使用for 语句遍历里面的孩子。关于string属性,如果超过一个标签的话,那么就会返回None,否则就返回具体的字符串print soup.title.string 就返回了 The Dormouse's story超过一个标签的话,可以试用strings向上查找可以用parent函数,如果查找所有的,那么可以使用parents函数查找下一个兄弟使用next_sibling,查找上一个兄弟节点使用previous_sibling,如果是查找所有的,那么在对应的函数后面加s就可以如何遍历树? 使用find_all 函数find_all(name, attrs, recursive, text, limit, **kwargs)举例说明:print soup.find_all('title')print soup.find_all('p','title')print soup.find_all('a')print soup.find_all(id="link2")print soup.find_all(id=True)返回值为:[<title>The Dormouse's story</title>][<p class="title"><b>The Dormouse's story</b></p>][<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>][<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>][<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]通过css查找,直接上例子把:print soup.find_all("a", class_="sister")print soup.select("p.title")通过属性进行查找print soup.find_all("a", attrs={"class": "sister"})通过文本进行查找print soup.find_all(text="Elsie")print soup.find_all(text=["Tillie", "Elsie", "Lacie"])限制结果个数print soup.find_all("a", limit=2)结果为:[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>][<p class="title"><b>The Dormouse's story</b></p>][<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>][u'Elsie'][u'Elsie', u'Lacie', u'Tillie'][<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>][code]find(name,attrs, recursive, text, **kwargs)
常见问题(Troubleshooting)
为什么Beautiful Soup不能打印我的no-ASCII字符?
If you're getting errors that say:,这个错误可能是Python的问题而不是BeautifulSoup。(译者注:在已知文档编码类型的情况下,可以先将编码转换为unicode形式,在转换为utf-8编码,然后才传递给BeautifulSoup。例如HTML的内容htm是GB2312编码:htm=unicode(htm,'gb2312','ignore').encode('utf-8','ignore')soup=BeautifulSoup(htm)如果不知道编码的类型,可以使用chardet先检测一下文档的编码类型。chardet需要自己安装一下,在网上很容下到。)[/code]"'ascii' codec can't encode character 'x' in position y: ordinal not in range(128)", the problem is probably with your Python installation rather than withBeautiful Soup. Try printing out the non-ASCII characters
withoutrunning them through Beautiful Soup and you should have the sameproblem. For instance, try running code like this:如果你遇到这样的错误:[code]"'ascii' codec can't encode character 'x' in position y: ordinal not in range(128)"
相关文章推荐
- 使用Python递归对文件进行相关处理
- python 安装 setuptools Compression requires the (missing) zlib module 的解决方案
- python scrapy
- Python的Django框架中的Cookie相关处理
- Python在windows下模拟按键和鼠标点击代码
- Python调用zip命令正确操作方法解析
- Python 异常继承体系
- ubuntu下mysql-python模块的安装
- ubuntu下为python安装BeautifulSoup
- Python中的变量、引用和作用域
- Python调用第三方接口实现nagios短信报警
- python 字符串
- 《Python 编程实战:运用设计模式、并发和程序库创建高质量程序》阅读笔记
- python的迭代器与生成器实例详解
- Python watchdog
- python 函数enumerate用法
- Python的zip函数
- 在Python的Django框架的视图中使用Session的方法
- python中的map、filter、reduce函数
- Python的Lambda函数与排序