1. 程式人生 > >運用Beautifulsoup對新聞網站進行簡單的爬取

運用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'的元素.

下面就對鳳凰網的一篇文章進行簡單的爬取:

# coding=utf-8
from urllib import request, parse
from bs4 import BeautifulSoup
import re

#網頁地址
url='http://news.ifeng.com/a/20181118/60165418_0.shtml'
#獲取web網頁
html=request.urlopen(url).read().decode('utf-8','ignore')
# 解析
soup=BeautifulSoup(html,'html.parser')

# 獲取資訊
page=soup.find('div',{'id':'artical'})
#根據所要爬取內容提取網頁中的CSS元素,如標題及內容
page_topic=page.find('h1',id='artical_topic')
#使用text屬性,提取標題和文字內容
topic=page_topic.get_text()
content=''
content=content+topic
page_content = page.find('div',id='main_content')
# contents=page_content.select('p')
for p in page_content.select('p'):
    content=content+p.get_text()
# print(topic)
# print('\r')
print(content)

這樣就可以實現對網頁新聞進行簡單的爬取了