利用BeautifulSoup爬取網頁內容

 

利用BeautifulSoup可以很簡單的爬取網頁上的內容。這個套件可以把一個網頁變成DOM Tree

要使用BeautifulSoup需要使用命令行進行安裝,不過也可以直接用python的ide。

基礎操作 :

使用之前需要先從bs4中導入包:from bs4 import BeautifulSoup

使用的代碼:soup = BeautifulSoup(res.text, 'html.parser')

括號中的第一個參數中的res是源網頁,res.text是源網頁的html,第二個參數'html.parser'是使用html的剖析器。、

可以使用select函數找出所有含有特定標籤的HTML元素,例如:soup.select('h1')可以找出所有含有h1標籤得到元素

它會返回一個list,這個list包含所有含'h1'的元素。

代碼:

soup = BeautifulSoup(res.text, 'html.parser')
h1 = soup.select('h1')
for h in h1:
    print(h)
#len = len(h1)
#for i in range(0,len):
#    print(h1[i])
#

④ 

可以使用select函數找出所有含有特定CSS屬性的元素,例如:

soup.select('#title')可以找出所有id爲title的元素(格式爲"#加上id名稱")

soup.select('#link')可以找出所有class爲title的元素(格式爲"#加上class名稱")

select返回的元素都是按照tag進行分類的,所以可以獲取到tag的值:

代碼:

a = '<a href = "#" abc = 456 def = 123> i am a link </a>'
soup = BeautifulSoup(a, 'html.parser')
print(soup.select('a')[0]['href'])#輸出"#"
print(soup.select('a')[0]['abc'])#輸出"456"
print(soup.select('a')[0]['def'])#輸出"123"

 

實戰(爬取新浪新聞資訊):

#導入包
import requests
from bs4 import BeautifulSoup
#爬取特定網頁
res = requests.get("https://news.sina.com.cn/china/")
#轉化文字編碼
res.encoding = 'utf-8'
#存進BeautifulSoup元素中
soup = BeautifulSoup(res.text, 'html.parser')
#print(soup)

for news in soup.select('.news-1'):#爬取並遍歷所有class爲"news_1”的元素
    li = news.select('li')#選取所有含有'li'特定標籤的元素,並存進li這個list中去
    num = len(li)#獲取到元素的個數
    if num > 0:
        for i in range(0, num):
            print(li[i].text)
            

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章