crawler(四):beautiful soup库

Beautiful Soup 简介

Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。官方解释如下:
Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。Beautiful Soup已成为和lxml、html6lib一样出色的python解释器,为用户灵活地提供不同的解析策略或强劲的速度。
Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更加强大,速度更快,推荐安装。

在这里插入图片描述

创建 Beautiful Soup 对象

首先必须要导入 bs4 库

from bs4 import BeautifulSoup

测试:

from  bs4  import  BeautifulSoup
import  re

html_doc = """
<html>
<head>
    <title>The Dormouse's story</title>
</head>
<body>
<p class="title aq">
    <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>
"""

#创建 beautifulsoup 对象
soup=BeautifulSoup(html_doc,'html.parser',from_encoding="utf-8")

#打印一下 soup 对象的内容,格式化输出
print(soup.prettify())

#输出第一个 title 标签
print(soup.title)
# <title>The Dormouse's story</title>

#输出第一个 title 标签的标签名称
print(soup.title.name)
#title

#输出第一个 title 标签的包含内容
print(soup.title.string)
# The Dormouse's story

#输出第一个 title 标签的父标签的标签名称
print(soup.title.parent.name)
#  head

#输出第一个  p 标签
print(soup.p)
"""
<p class="title aq">
<b>
        The Dormouse's story
    </b>
</p>
"""

#输出第一个  p 标签的 class 属性内容
print(soup.p["class"])
# ['title', 'aq']

#输出第一个  a 标签的  href 属性内容
print(soup.a['href'])
# http://example.com/elsie

'''
soup的属性可以被添加,删除或修改. 再说一次, soup的属性操作方法与字典一样
'''
#修改第一个 a 标签的href属性为 http://www.baidu.com/
soup.a['href']='http://www.baidu.com/'

#给第一个 a 标签添加 name 属性
soup.a["name"]=u'百度'

#删除第一个a标签的class属性
del soup.a['class']

#输出第一个  p 标签的所有子节点
print(soup.p.contents)
"""
['\n', <b>
        The Dormouse's story
    </b>, '\n']
"""


#输出第一个  a 标签
print(soup.a)
#<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

#输出所有的  a 标签,以列表形式显示
print(soup.find_all('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>]
"""

#输出第一个 id 属性等于  link3 的  a 标签
print(soup.find(id='link3'))
#<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>

#获取所有文字
print(soup.get_text())
"""
The Dormouse's story




        The Dormouse's story
    

Once upon a time there were three little sisters; and their names were
    Elsie,
    Lacie 
    and
    Tillie;
    and they lived at the bottom of a well.

...
"""

#输出第一个  a 标签的所有属性信息
print(soup.a.attrs)
# {'href': 'http://example.com/elsie', 'class': ['sister'], 'id': 'link1'}
for link in soup.find_all('a'):
    #获取 link 的  href 属性内容
    print(link.get('href'))  #print(link["href"]) 也可以

    """
    http://example.com/elsie
    http://example.com/lacie
    http://example.com/tillie
    """

#对soup.p的子节点进行循环输出
for child in soup.p.children:
    print(child)
    """
    <b>
        The Dormouse's story
    </b>
    """

#正则匹配,名字中带有b的标签
for tag in soup.find_all(re.compile("b")):
    print(tag.name)
    # body
    # b

四大对象种类

Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:

1. Tag
2. NavigableString
3. BeautifulSoup
4. Comment

在这里插入图片描述

Tag

Tag 是什么?通俗点讲就是 HTML 中的一个个标签,例如

<title>The Dormouse's story</title>
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

上面的 title a 等等 HTML 标签加上里面包括的内容就是 Tag

用 Beautiful Soup 来方便地获取 Tags

print soup.title
#<title>The Dormouse's story</title>
 
print soup.head
#<head><title>The Dormouse's story</title></head>
 
print soup.a
#<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
 
print soup.p
#<p class="title" name="dromouse"><b>The Dormouse's story</b></p>

利用 soup加标签名轻松地获取这些标签的内容,不过有一点是,它查找的是在所有内容中的第一个符合要求的标签,soup.title得到的是title标签,soup.p得到的是文档中的第一个p标签,要想得到所有标签,得用find_all函数find_all 函数返回的是一个序列,可以对它进行循环,依次得到想到的东西.。
对于 Tag,它有两个重要的属性,是 name 和 attrs

print soup.name
print soup.head.name
#[document]
#head

soup 对象本身比较特殊,它的 name 即为 [document],对于其他内部标签,输出的值便为标签本身的名称。

print soup.p.attrs
#{'class': ['title'], 'name': 'dromouse'}

在这里,我们把 p 标签的所有属性打印输出了出来,得到的类型是一个字典。如果我们想要单独获取某个属性,可以这样,例如我们获取它的 class 叫什么

print soup.p['class']
#['title']

还可以这样,利用get方法,传入属性的名称,二者是等价的

print soup.p.get('class')
#['title']
NavigableString

既然我们已经得到了标签的内容,那么问题来了,我们要想获取标签内部的文字怎么办呢?很简单,用.string即可,例如

print (soup.p.string)
#The Dormouse's story

这样我们就轻松获取到了标签里面的内容,想想如果用正则表达式要多麻烦。它的类型是一个 NavigableString,翻译过来叫 可以遍历的字符串

BeautifulSoup

BeautifulSoup 对象表示的是一个文档的全部内容.大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性

print type(soup.name)
#<type 'unicode'>
print soup.name 
# [document]
print soup.attrs 
#{} 空字典
Comment

Comment 对象是一个特殊类型的 NavigableString 对象,其实输出的内容仍然不包括注释符号,但是如果不好好处理它,可能会对我们的文本处理造成意想不到的麻烦。

print soup.a
print soup.a.string
print type(soup.a.string)

输出:

<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
 Elsie 
<class 'bs4.element.Comment'>

a 标签里的内容实际上是注释,但是如果我们利用 .string 来输出它的内容,我们发现它已经把注释符号去掉了,所以这可能会给我们带来不必要的麻烦。

常见的四种对象:

  1. Tag:BeautifulSoup中所有的标签都是Tag类型,并且BeautifulSoup的对象其实本质上也是一个Tag类型。所以其实一些方法比如find、find_all并不是BeautifulSoup的,而是Tag的。
  2. NavigableString:继承自python中的str,用起来就跟使用python的str是一样的。
  3. BeautifulSoup:继承自Tag。用来生成BeaufifulSoup树的。对于一些查找方法,比如find、select这些,其实还是Tag的。
  4. Comment:这个也没什么好说,就是继承自NavigableString。

遍历文档树

直接子节点

Tag.Tag_child1:直接通过下标名称访问子节点。

Tag.contents:以列表形式返回所有子节点。

Tag.children:生成器,可用于循环访问:for child in Tag.children

.contents
tag 的 .content 属性可以将tag的子节点以列表的方式输出。可以使用 [num] 的形式获得。使用contents向后遍历树,使用parent向前遍历树

print soup.head.contents 
#[<title>The Dormouse's story</title>]

输出方式为列表,我们可以用列表索引来获取它的某一个元素

print soup.head.contents[0]
#<title>The Dormouse's story</title>

.children
它返回的不是一个 list,不过我们可以通过遍历获取所有子节点。我们打印输出 .children 看一下,可以发现它是一个 list 生成器对象。
可以使用list可以将其转化为列表。当然可以使用for 语句遍历里面的孩子。

print soup.head.children
#<listiterator object at 0x7f71457f5710>

contentschildren
返回某个标签下的直接子元素,其中也包括字符串。他们两的区别是:contents返回来的是一个列表,children返回的是一个迭代器。

获得里面的内容呢?很简单,遍历一下就好了

for child in  soup.body.children:
    print child

所有子孙节点

.descendants属性
.descendants
.contents.children 属性仅包含tag的直接子节点,.descendants 属性可以对所有tag的子孙节点进行递归循环,和 children类似,我们也需要遍历获取其中的内容。

for child in soup.descendants:
    print child

节点内容

知识点:.string 属性

  • Tag.String:Tag只有一个String子节点是,可以这么访问,否则返回None
  • Tag.Strings:生成器,可用于循环访问:for str in Tag.Strings

如果tag只有一个 NavigableString 类型子节点,那么这个tag可以使用 .string 得到子节点。如果一个tag仅有一个子节点,那么这个tag也可以使用 .string 方法,输出结果与当前唯一子节点的 .string 结果相同。通俗点说就是:如果一个标签里面没有标签了,那么 .string 就会返回标签里面的内容。如果标签里面只有唯一的一个标签了,那么 .string 也会返回最里面的内容。如果超过一个标签的话,那么就会返回None。

print soup.head.string
#The Dormouse's story
print soup.title.string
#The Dormouse's story

如果tag包含了多个子节点,tag就无法确定,string 方法应该调用哪个子节点的内容, .string 的输出结果是 None

print soup.html.string
# None

多个内容·

知识点:strings .stripped_strings属性
.strings
获取多个内容,不过需要遍历获取,比如下面的例子

for string in soup.strings:
    print(repr(string))

.stripped_strings
输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白内容

for string in soup.stripped_strings:
    print(string)
    """
    The Dormouse's story
    The Dormouse's story
    Once upon a time there were three little sisters; and their names were
    Elsie
    ,
    Lacie
    and
    Tillie
    ;
        and they lived at the bottom of a well.
    ...

    """

父节点

知识点:.parent属性
使用parent获取父节点。
Tag.parent:父节点
Tag.parents:父到根的所有节点

body = soup.body
html = body.parent             # html是body的父亲
p = soup.p
print p.parent.name
#body
 
content = soup.head.title.string
print content.parent.name
#title

全部父节点

知识点:.parents属性
通过元素的 .parents 属性可以递归得到元素的所有父辈节点,例如

content = soup.head.title.string
for parent in  content.parents:
    print parent.name
 
title
head
html
[document]

可以通过.操作访问子节点content = soup.head.title.string

兄弟节点

知识点:.next_sibling .previous_sibling 属性
使用nextSibling, previousSibling获取前后兄弟
Tag.next_sibling
Tag.next_siblings
Tag.previous_sibling
Tag.previous_siblings
兄弟节点可以理解为和本节点处在统一级的节点,.next_sibling属性获取了该节点的下一个兄弟节点,.previous_sibling 则与之相反,如果节点不存在,则返回 None。
注意:实际文档中的tag的 .next_sibling 和 .previous_sibling 属性通常是字符串或空白,因为空白或者换行也可以被视作一个节点,所以得到的结果可能是空白或者换行

print soup.p.next_sibling
#       实际该处为空白
print soup.p.prev_sibling
#None   没有前一个兄弟节点,返回 None
print soup.p.next_sibling.next_sibling

.next方法:只能针对单一元素进行.next,或者说是对contents列表元素的挨个清点。

比如
soup.contents[1]=u'HTML'
soup.contents[2]=u'\n'

全部兄弟节点

知识点:.next_siblings .previous_siblings属性
通过 .next_siblings.previous_siblings属性可以对当前节点的兄弟节点迭代输出

前后节点

知识点:.next_element .previous_element 属性
与 .next_sibling .previous_sibling 不同,它并不是针对于兄弟节点,而是在所有节点,不分层次。比如 head 节点为

<head><title>The Dormouse's story</title></head>

那么它的下一个节点便是 title,它是不分层次关系的

print soup.head.next_element
#<title>The Dormouse's story</title>

所有前后节点

知识点:.next_elements .previous_elements 属性
通过.next_elements.previous_elements 的迭代器就可以向前或向后访问文档的解析内容,就好像文档正在被解析一样

for element in last_a_tag.next_elements:
    print(repr(element))

搜索文档树

最常用的是find_all()函数

find_all()函数

find_all( name , attrs , recursive , text , **kwargs )
find_all() 方法搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件
1)name 参数
name 参数可以查找所有名字为 name 的tag,字符串对象会被自动忽略掉

#第一个参数为Tag的名称 
tag.find_all(‘title’)  
#得到”<title>&%^&*</title>”,结果为一个列表  
 
第二个参数为匹配的属性
tag.find_all(“title”,class=”sister”)  
#得到如”<title class = “sister”>%^*&</title>  
 
# 第二个参数也可以为字符串,得到字符串匹配的结果
tag.find_all(“title”,”sister”)  
#得到如”<title class = “sister”>%^*&</title>  
  • 传字符串
    最简单的过滤器是字符串.在搜索方法中传入一个字符串参数,Beautiful Soup会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的<b>标签

    for i in soup.find_all('b'):
        print(i)
        """
        <b>
            The Dormouse's story
        </b>
        """
    for i in soup.find('b'):
        print(i)
        """
        
            The Dormouse's story
        
    
        """
    
    
  • 传正则表达式
    如果传入正则表达式作为参数,Beautiful Soup会通过正则表达式的 match() 来匹配内容.下面例子中找出所有以b开头的标签,这表示<body><b>标签都应该被找到

    import re
    for tag in soup.find_all(re.compile("^b")):
        print(tag.name)
    # body
    # b
    
  • 传列表
    如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有<a>标签和<b>标签

soup.find_all(["a", "b"])
"""
[<b>The Dormouse's story</b>,
<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>]
"""
  • 传 True
    True 可以匹配任何值,下面代码查找到所有的tag,但是不会返回字符串节点
    for tag in soup.find_all(True):
        print(tag.name)
    # html
    # head
    # title
    # body
    # p
    # b
    # p
    # a
    # a
    
  • 传方法
    如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数 [4] ,如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False。下面方法校验了当前元素,如果包含 class 属性却不包含 id 属性,那么将返回 True:
def has_class_but_no_id(tag):
    return tag.has_attr('class') and not tag.has_attr('id')

将这个方法作为参数传入find_all() 方法,将得到所有<p>标签:

soup.find_all(has_class_but_no_id)
# [<p class="title"><b>The Dormouse's story</b></p>,
#  <p class="story">Once upon a time there were...</p>,
#  <p class="story">...</p>]
  • keyword 参数
    注意:如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字tag的属性来搜索,如果包含一个名字为 id 的参数,Beautiful Soup会搜索每个tag的”id”属性
soup.find_all(id='link2')
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

如果传入 href 参数,Beautiful Soup会搜索每个tag的”href”属性

soup.find_all(href=re.compile("elsie"))
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]

使用多个指定名字的参数可以同时过滤tag的多个属性

soup.find_all(href=re.compile("elsie"), id='link1')
# [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]

在这里我们想用 class 过滤,不过 class 是 python 的关键词,这怎么办?加个下划线就可以

soup.find_all("a", class_="sister")
# [<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>]
  • text 参数
    通过 text 参数可以搜搜文档中的字符串内容.与 name 参数的可选值一样, text 参数接受 字符串 , 正则表达式 , 列表, True
    通过 text 参数可以搜搜文档中的字符串内容.与 name 参数的可选值一样, text 参数接受 字符串 , 正则表达式 , 列表, True

    soup.find_all(text="Elsie")
    #[u'Elsie']
     
    soup.find_all(text=["Tillie", "Elsie", "Lacie"])
    #[u'Elsie', u'Lacie', u'Tillie']
     
    soup.find_all(text=re.compile("Dormouse"))
    [u"The Dormouse's story", u"The Dormouse's story"]
    
  • limit 参数
    find_all() 方法返回全部的搜索结构,如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果.
    文档树中有3个tag符合搜索条件,但结果只返回了2个,因为我们限制了返回数量

    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>]
    
  • recursive 参数
    调用tag的 find_all() 方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False 。一段简单的文档:

<html>
 <head>
  <title>
   The Dormouse's story
  </title>
 </head>
...

是否使用 recursive 参数的搜索结果:

soup.html.find_all("title")
# [<title>The Dormouse's story</title>]
 
soup.html.find_all("title", recursive=False)
# []

find()函数

find(name=None, attrs={}, recursive=True, text=None, **kwargs)
它与find_all()方法唯一的区别是 find_all()方法的返回结果是值包含一个元素的列表,而 find()方法直接返回结果。
.find('p'),.findAll('p'):find返回的是字符串值,而且是返回从头查找到的第一个tag对。但是如果这第一个tag对包括大量的内容,父等级很高,则同时其内部所包含的,此级标签也全部都find。findAll返回值是个列表,如果发现了一个同名标签内含多个同名标签,则内部的标签一并归于该父标签显示,列表其他元素也不再体现那些内含的同名子标签。即findAll会返回所有符合要求的结果,并以list返回。

tag搜索
find(tagname)                                  # 直接搜索名为tagname的tag 如:find('head')
find(list)                                     # 搜索在list中的tag,如: find(['head', 'body'])
find(dict)                                     # 搜索在dict中的tag,如:find({'head':True, 'body':True})
find(re.compile(''))                           # 搜索符合正则的tag, 如:find(re.compile('^p')) 搜索以p开头的tag
find(lambda)                       # 搜索函数返回结果为true的tag, 如:find(lambda name: if len(name) == 1) 搜索长度为1的tag
find(True)                                     # 搜索所有tag
 
attrs搜索
find(id='xxx')                                  # 寻找id属性为xxx的
find(attrs={id=re.compile('xxx'), algin='xxx'}) # 寻找id属性符合正则且algin属性为xxx的
find(attrs={id=True, algin=None})               # 寻找有id属性但是没有algin属性的
 
resp1 = soup.findAll('a', attrs = {'href': match1})
resp2 = soup.findAll('h1', attrs = {'class': match2})
resp3 = soup.findAll('img', attrs = {'id': match3})
 
text搜索
   文字的搜索会导致其他搜索给的值如:tag, attrs都失效。方法与搜索tag一致   
print p1.text
# u'This is paragraphone.'
print p2.text
# u'This is paragraphtwo.'
# 注意:1,每个tag的text包括了它以及它子孙的text。2,所有text已经被自动转为unicode,如果需要,可以自行转码encode(xxx)
 
recursive和limit属性
recursive=False表示只搜索直接儿子,否则搜索整个子树,默认为True。
当使用findAll或者类似返回list的方法时,limit属性用于限制返回的数量,
如:findAll('p', limit=2): 返回首先找到的两个tag
find_all的使用:
  1. 在提取标签的时候,第一个参数是标签的名字。然后如果在提取标签的时候想要使用标签属性进行过滤,那么可以在这个方法中通过关键字参数的形式,将属性的名字以及对应的值传进去。或者是使用attrs属性,将所有的属性以及对应的值放在一个字典中传给attrs属性。
  2. 有些时候,在提取标签的时候,不想提取那么多,那么可以使用limit参数。限制提取多少个。
find与find_all的区别:
  1. find:找到第一个满足条件的标签就返回。说白了,就是只会返回一个元素。
  2. find_all:将所有满足条件的标签都返回。说白了,会返回很多标签(以列表的形式)。
使用find和find_all的过滤条件:
  1. 关键字参数:将属性的名字作为关键字参数的名字,以及属性的值作为关键字参数的值进行过滤。
  2. attrs参数:将属性条件放到一个字典中,传给attrs参数。
获取标签的属性:
  1. 通过下标获取:通过标签的下标的方式。
    href = a['href']
    
  2. 通过attrs属性获取:示例代码:
    href = a.attrs['href']
    
    
stringstringsstripped_strings属性以及get_text方法:
  1. string:获取某个标签下的非标签字符串。返回来的是个字符串。如果这个标签下有多行字符,那么就不能获取到了。
  2. strings:获取某个标签下的子孙非标签字符串。返回来的是个生成器。
  3. stripped_strings:获取某个标签下的子孙非标签字符串,会去掉空白字符。返回来的是个生成器。
  4. get_text:获取某个标签下的子孙非标签字符串。不是以列表的形式返回,是以普通字符串返回。
#encoding: utf-8

from bs4 import BeautifulSoup

html = """
<table class="tablelist" cellpadding="0" cellspacing="0">
    <tbody>
        <tr class="h">
            <td class="l" width="374">职位名称</td>
            <td>职位类别</td>
            <td>人数</td>
            <td>地点</td>
            <td>发布时间</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=33824&keywords=python&tid=87&lid=2218">22989-金融云区块链高级研发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-25</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a target="_blank" href="position_detail.php?id=29938&keywords=python&tid=87&lid=2218">22989-金融云高级后台开发</a></td>
            <td>技术类</td>
            <td>2</td>
            <td>深圳</td>
            <td>2017-11-25</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=31236&keywords=python&tid=87&lid=2218">SNG16-腾讯音乐运营开发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>2</td>
            <td>深圳</td>
            <td>2017-11-25</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a target="_blank" href="position_detail.php?id=31235&keywords=python&tid=87&lid=2218">SNG16-腾讯音乐业务运维工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-25</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=34531&keywords=python&tid=87&lid=2218">TEG03-高级研发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a target="_blank" href="position_detail.php?id=34532&keywords=python&tid=87&lid=2218">TEG03-高级图像算法研发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=31648&keywords=python&tid=87&lid=2218">TEG11-高级AI开发工程师(深圳)</a></td>
            <td>技术类</td>
            <td>4</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a target="_blank" href="position_detail.php?id=32218&keywords=python&tid=87&lid=2218">15851-后台开发工程师</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="even">
            <td class="l square"><a target="_blank" href="position_detail.php?id=32217&keywords=python&tid=87&lid=2218">15851-后台开发工程师</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
        <tr class="odd">
            <td class="l square"><a id="test" class="test" target='_blank' href="position_detail.php?id=34511&keywords=python&tid=87&lid=2218">SNG11-高级业务运维工程师(深圳)</a></td>
            <td>技术类</td>
            <td>1</td>
            <td>深圳</td>
            <td>2017-11-24</td>
        </tr>
    </tbody>
</table>
"""


# 1. 获取所有tr标签
# 2. 获取第2个tr标签
# 3. 获取所有class等于even的tr标签
# 4. 将所有id等于test,class也等于test的a标签提取出来。
# 5. 获取所有a标签的href属性
# 6. 获取所有的职位信息(纯文本)

soup = BeautifulSoup(html,'lxml')

# 1. 获取所有tr标签
# trs = soup.find_all('tr')
# for tr in trs:
#     print(tr)
#     print('='*30)

# # 2. 获取第2个tr标签
# tr = soup.find_all('tr',limit=2)[1]
# print(tr)

# 3. 获取所有class等于even的tr标签
# atrribute
# trs = soup.find_all('tr',attrs={'class':"even"})
# for tr in trs:
#     print(tr)
#     print('='*30)

# 4. 将所有id等于test,class也等于test的a标签提取出来。
# aList = soup.find_all('a',id='test',class_='test')
# aList = soup.find_all('a',attrs={"id":"test","class":"test"})
# for a in aList:
#     print(a)

# 5. 获取所有a标签的href属性
# aList = soup.find_all('a')
# for a in aList:
#     # 1. 通过下表操作的方式
#     # href = a['href']
#     # print(href)
#     # 2. 通过attrs属性的方式
#     href = a.attrs['href']
#     print(href)

# 6. 获取所有的职位信息(纯文本)
# trs = soup.find_all('tr')[1:]
# movies = []
# for tr in trs:
#     movie = {}
#     # tds = tr.find_all("td")
#     # title = tds[0].string
#     # category = tds[1].string
#     # nums = tds[2].string
#     # city = tds[3].string
#     # pubtime = tds[4].string
#     # movie['title'] = title
#     # movie['category'] = category
#     # movie['nums'] = nums
#     # movie['city'] = city
#     # movie['pubtime'] = pubtime
#     # movies.append(movie)
#
#     infos = list(tr.stripped_strings)
#     movie['title'] = infos[0]
#     movie['category'] = infos[1]
#     movie['nums'] = infos[2]
#     movie['city'] = infos[3]
#     movie['pubtime'] = infos[4]
#     movies.append(movie)
#
# print(movies)

tr = soup.find_all('tr')[1]
text = tr.string
print(text)

select方法:

使用以上方法可以方便的找出元素。但有时候使用css选择器的方式可以更加的方便。使用css选择器的语法,应该使用select方法。以下列出几种常用的css选择器方法:

  1. 通过标签名查找:

    print(soup.select('a'))
    
  2. 通过类名查找:
    通过类名,则应该在类的前面加一个.。比如要查找class=sister的标签。示例代码如下:

    print(soup.select('.sister'))
    
  3. 通过id查找:
    通过id查找,应该在id的名字前面加一个号。示例代码如下:

    print(soup.select("#link1"))
    
  4. 组合查找:
    组合查找即和写 class 文件时,标签名与类名、id名进行的组合原理是一样的,例如查找 p 标签中,id 等于 link1的内容,二者需要用空格分开:

    print(soup.select("p #link1"))
    

    直接子标签查找,则使用 >分隔:

    print(soup.select("head > title"))
    
  5. 通过属性查找:
    查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。示例代码如下:

    print(soup.select('a[href="http://example.com/elsie"]'))
    
  6. 获取内容
    以上的 select 方法返回的结果都是列表形式,可以遍历形式输出,然后用get_text()方法来获取它的内容。

    soup = BeautifulSoup(html, 'lxml')
    print type(soup.select('title'))
    print soup.select('title')[0].get_text()
    
    for title in soup.select('title'):
        print title.get_text()
    

CSS选择器(补充):

  1. 根据标签的名字选择,示例代码如下:
    p{
        background-color: pink;
    }
    
  2. 根据类名选择,那么要在类的前面加一个点。示例代码如下:
    .line{
        background-color: pink;
    }
    
  3. 根据id名字选择,那么要在id的前面加一个#号。示例代码如下:
    #box{
        background-color: pink;
    }
    
  4. 查找子孙元素。那么要在子孙元素中间有一个空格。示例代码如下:
    #box p{
        background-color: pink;
    }
    
  5. 查找直接子元素。那么要在父子元素中间有一个>。示例代码如下:
    #box > p{
        background-color: pink;
    }
    
  6. 根据属性的名字进行查找。那么应该先写标签名字,然后再在中括号中写属性的值。示例代码如下:
    input[name='username']{
        background-color: pink;
    }
    
  7. 在根据类名或者id进行查找的时候,如果还要根据标签名进行过滤。那么可以在类的前面或者id的前面加上标签名字。示例代码如下:
    div#line{
        background-color: pink;
    }
    div.line{
        background-color: pink;
    }
    

中国天气网数据爬取

#encoding: utf-8

import requests
from bs4 import BeautifulSoup
from pyecharts import Bar

ALL_DATA = []

def parse_page(url):
    headers = {
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"
    }
    response = requests.get(url,headers=headers)
    text = response.content.decode('utf-8')
    # html5lib
    # pip install html5lib
    soup = BeautifulSoup(text,'html5lib')
    conMidtab = soup.find('div',class_='conMidtab')
    tables = conMidtab.find_all('table')
    for table in tables:
        trs = table.find_all('tr')[2:]
        for index,tr in enumerate(trs):
            tds = tr.find_all('td')
            city_td = tds[0]
            if index == 0:
                city_td = tds[1]
            city = list(city_td.stripped_strings)[0]
            temp_td = tds[-2]
            min_temp = list(temp_td.stripped_strings)[0]
            ALL_DATA.append({"city":city,"min_temp":int(min_temp)})
            # print({"city":city,"min_temp":int(min_temp)})

def main():
    urls = [
        'http://www.weather.com.cn/textFC/hb.shtml',
        'http://www.weather.com.cn/textFC/db.shtml',
        'http://www.weather.com.cn/textFC/hd.shtml',
        'http://www.weather.com.cn/textFC/hz.shtml',
        'http://www.weather.com.cn/textFC/hn.shtml',
        'http://www.weather.com.cn/textFC/xb.shtml',
        'http://www.weather.com.cn/textFC/xn.shtml',
        'http://www.weather.com.cn/textFC/gat.shtml'
    ]
    for url in urls:
        parse_page(url)

    # 分析数据
    # 根据最低气温进行排序
    ALL_DATA.sort(key=lambda data:data['min_temp'])

    data = ALL_DATA[0:10]
    cities = list(map(lambda x:x['city'],data))
    temps = list(map(lambda x:x['min_temp'],data))
    # pyecharts
    # pip install pyecharts
    chart = Bar("中国天气最低气温排行榜")
    chart.add('',cities,temps)
    chart.render('temperature.html')


if __name__ == '__main__':
    main()
    # ALL_DATA = [
    #     {"city": "北京", 'min_temp': 0},
    #     {"city": "天津", 'min_temp': -8},
    #     {"city": "石家庄", 'min_temp': -10}
    # ]
    #
    # ALL_DATA.sort(key=lambda data:data['min_temp'])
    # print(ALL_DATA)
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
根据引用和引用的代码内容来看,似乎是由于在代码中修改了引用的内容,导致出现了AttributeError错误。具体来说,错误信息是说'Crawler'对象没有'url'属性。这可能是因为在代码中,Crawler对象被错误地使用了'url'属性,而实际上'Crawler'对象应该使用其他属性来获取URL。为了解决这个错误,你需要检查代码中'Crawler'对象的使用,并确保使用了正确的属性来获取URL。 对于这个问题,你可以检查以下几个方面: 1. 检查代码中是否存在其他地方错误地使用了'Crawler'对象的'url'属性。可能是其他代码部分引起了这个错误。 2. 确保代码中使用了正确的属性来获取URL。可以参考Scrapy官方文档或其他相关文档,查看正确的属性和方法来获取URL。 3. 确认Scrapy已正确安装,可以尝试重新安装Scrapy,或者检查Scrapy的版本是否与代码兼容。 综上所述,你可以根据以上建议检查和修改代码,以解决AttributeError错误。如果问题仍然存在,可能需要进一步调试和排查代码。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [scrapy_AttributeError: 'generator' object has no attribute 'meta'''_'generator' 'dont_filter'](https://blog.csdn.net/jss19940414/article/details/85267727)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [AttributeError: 'module' object has no attribute 'Spider' 解决了](https://blog.csdn.net/zouxfbj/article/details/76602188)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值