天天看點

python新聞文本爬蟲_Python 爬蟲進階篇-利用beautifulsoup庫爬取網頁文章内容實戰示範...

我們以

fox新聞 網的文章來舉例子,把整篇文章爬取出來。

首先是标題,通過結構可以看出來

class 為

article-header 的節點下的

h1 裡的内容即是标題,通過

string 可以擷取

dom 節點裡的文本内容。

# 擷取文章标題alert_header = soup.find('header', class_="article-header").find('h1')print(alert_header.string)123

python新聞文本爬蟲_Python 爬蟲進階篇-利用beautifulsoup庫爬取網頁文章内容實戰示範...

然後是正文,通過結構可以看出來

class 為

article-body 的節點下的

p 元素組成了正文内容,通過

contents 可以擷取

body 下所有的節點。再周遊所有的節點,把所有

p 元素的下的内容列印出來。

python新聞文本爬蟲_Python 爬蟲進階篇-利用beautifulsoup庫爬取網頁文章内容實戰示範...

from urllib.request import urlopenfrom bs4 import BeautifulSoup

url = urlopen('https://www.foxnews.com/tech/mom-received-dirty-diapers-amazon')soup = BeautifulSoup(url, 'html.parser') # parser 解析# 擷取文章标題alert_header = soup.find('header', class_="article-header").find('h1')print("标題如下:")print(alert_header.string)# 擷取文章正文alert_body = soup.find('div', class_="article-body").contents # 所有body裡的p節點# 列印文章正文print("正文如下:")for i in alert_body:

if(i.name == "p"):

print(i.getText())

print()1234567891011121314151617181920

運作效果圖:

如果中間夾雜了廣告,可以看看文章正文跟廣告在結構上有什麼差別,然後進一步把廣告剔除。

python新聞文本爬蟲_Python 爬蟲進階篇-利用beautifulsoup庫爬取網頁文章内容實戰示範...