BeautifulSoup4----利用find_all和get方法來獲取信息

<html>
    <head>
        <title>Page title</title>
    </head>
    <body>
        <p id="firstpara" align="center">
        This is paragraph<b>one</b>.
        </p>
        <p id="secondpara" align="blah">
        This is paragraph<b>two</b>.
        </p>
     </body>
</html>
  • find方法的參數及意義

find(name=None, attrs={}, recursive=True, text=None, **kwargs)html

1,按照tag(標籤)搜索:git

1 find(tagname)        # 直接搜索名爲tagname的tag 如:find('head')
2 find(list)           # 搜索在list中的tag,如: find(['head', 'body'])
3 find(dict)           # 搜索在dict中的tag,如:find({'head':True, 'body':True})
4 find(re.compile('')) # 搜索符合正則的tag, 如:find(re.compile('^p')) 搜索以p開頭的tag
5 find(lambda)         # 搜索函數返回結果爲true的tag, 如:find(lambda name: if len(name) == 1) 搜索長度爲1的tag
6 find(True)           # 搜索全部tag

  2,按照attrs(屬性)搜索:github

1 find('id'='xxx')                                  # 尋找id屬性爲xxx的
2 find(attrs={'id':re.compile('xxx'), 'algin':'xxx'}) # 尋找id屬性符合正則且algin屬性爲xxx的
3 find(attrs={'id':True, 'algin':None})               # 尋找有id屬性可是沒有algin屬性的

 

  • 利用BeautifulSoup4爬取豆瓣數據的ID

代碼以下:編程

import requests
from bs4 import BeautifulSoup as bs

#以豆瓣‘編程’分類的一個鏈接URL爲例子開始爬數據ID
url = 'https://book.douban.com/tag/編程?start=20&type=T'
res = requests.get(url)  #發送請求
#print(res.encoding)    #這個是用來查看網頁編碼的
#res.encoding = 'utf-8'   #跟上一個結合來用,若是編碼有亂碼,則能夠經過這個定義編碼來改變
html = res.text     
#print(html)

IDs = []
soup  = bs(html,"html.parser")     #定義一個BeautifulSoup變量
items = soup.find_all('a',attrs={'class':'nbg'})
#print(items)

for i in items:
    idl = i.get('href')
    #print(idl)
    id = idl.split('/')[4]
    print(id)
    IDs.append(id)
print('這一頁收集到書籍ID數:%d' % len(IDs))

 

 

  • 第一部分是獲取網頁源代碼的過程,使用requests模塊
  • 第二部分爲使用BeautifulSoup來解析網頁,獲得須要的信息
    • soup  = bs(html,"html.parser")

      這句的意思是聲明一個變量,用BeautifulSoup處理以後的原網頁代碼app

    • items = soup.find_all('a',attrs={'class':'nbg'})

      這句的做用是查找a標籤,固然,a標籤會有不少,可是咱們不須要全部,所以咱們還須要判斷一下這種a標籤還有個屬性是class='nbg',咱們只須要這種a標籤。items獲得的是一個listide

    • 屬性都放着attrs這個字典中,當某個屬性的值不是定值的時候,可使用   '屬性名':True  這種方式。
    • for i in items:
          idl = i.get('href')

      這句的意思是獲取知足條件的每一個a標籤中屬性‘href’的值函數

    • id = idl.split('/')[4]

      因爲‘href’的屬性是一個鏈接,可是咱們只須要獲得ID,全部能夠將鏈接按照‘/’分解,提取ID編碼

  • 具體的爬蟲例子能夠參照:智聯招聘爬蟲

  • Beautifulsoup的select選擇器方法能夠參考爬蟲例子:前程無憂爬蟲

相關文章
相關標籤/搜索