python 爬虫(二)

python 爬虫 Advanced HTML Parsing

1. 通过属性查找标签:基本上在每一个网站上都有stylesheets,针对于不同的标签会有不同的css类于之向对应在我们看到的标签可能是像下面这样的

  <span class="green" ></span> <span class="red"></span>

    通过标签的class我们的程序能够简单的将他们分辨开来。

1 from urllib.request import urlopen
2 from bs4 import BeautifulSoup
3 
4 html = urlopen("http://www.pythonscraping.com/pages/warandpeace.html")
5 bsObj = BeautifulSoup(html,"html.parser")
6 
7 nameList = bsObj.find_all("span",{"class":"green"})
8 for name in nameList:
9     print(name.get_text())

    运行上面的脚本会将所有class为green的标签找出来,并且打印出来他们的context

    I  find_all方法:

         find_all(name,attrs,recursive,text,**kwargs)

   name参数:用来查找名字为name的标签,字符串对象会被忽略掉。这个name参数的值可以使用任意一种过滤器:

         1. 字符串,在查找方法中BeautifulSoup会查找与字符串完全匹配的内容

      soup.find_all('span')

          2. 正则表达式,BeautifulSoup会通过正则表达式的match来匹配内容

      soup.find_all(re.compile("b")) # body b

          3 列表:如果传入的是列表,beautifulSoup会将列表中所有元素匹配返回

      soup.find_all(['a','b'])

           4 True,返回所有标签

           5 方法,如果没有合适的过滤器还可以定义一个方法,这个方法只能接受一个参数,如果方法返回为True表示当前元素匹配并且被找到,如果不是返回false

1 def has_class_but_no_id(tag):
2     return tag.has_attr('class') and not tag.has_attr('id')
3 bsObj.find(has_class_but_no_id)
View Code

           keyword参数

           如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当做指定名字的标签的属性来搜索

 

其实这章主要是对BeautifulSoup的介绍:详细信息可见

    soup.find_all(id='link2')

           soup.find_all(href=re.compile("slsie"))

    soup.find_all(id = True)所有有id的标签

           搜索指定名字的属性可以是  字符串 正则表达式 列表 True

    使用多个指定名称参数同时过滤

    soup.find_all(href=re.compile("elsie"),id="link")

          有些tag的属性不能够在搜索中使用 比如data-*

1 data_soup = BeautifulSoup('<div data-foo="value">foo!</div>')
2 data_soup.find_all(data-foo="value")
3 # SyntaxError: keyword can't be an expression

    text参数:

    通过text参数可以搜搜文档中字符串的内容,和name的使用方式基本一样

           limit参数:

    find_all返回全部的搜索结果,如果文档树很大,那么搜索的结果会比较慢可以使用limit控制返回的数量

    revursive参数

    调用find_all的时候会搜索当前所有的子孙节点,如果只想搜索直接子节点使用recursive=False

    II find方法

   find方法和find_all方法在使用上基本相同,find返回一个标签find_all返回一个标签列表

         在找的值为空的情况下find_all返回一个空列表find返回None

        

posted @ 2016-12-28 16:10  someOneHan  阅读(210)  评论(0编辑  收藏  举报