python爬取搜狐網的新聞

2022-07-26 16:54:11 字數 1899 閱讀 4800

1

import

requests

2from bs4 import

beautifulsoup3#

4 newsurl = '

'5#用get方法進行網頁獲取

6 res =requests.get(newsurl)7#

用utf-8的編碼方式

8 res.encoding='

utf-8'9

#獲取網頁的內容,並用html.parser剖析器

10 soup = beautifulsoup(res.text,"

html.parser")

11#獲取到class=news下的內容,因為他現在是乙個集合所以不能直接用text,必須用for迴圈的形式把集合中的物件取出來這對這個物件用text

12 div = soup.select('

.news')

13 content ={}

14 href ={}

15for news in

div:

16if len(news.select('

p'))>0:17#

獲取到p標籤下的內容

18 p = news.select('p'

)19#把內容進行迴圈

20for p1 in

p:21

#列印出內容中的文字

22print

(p1.text)23#

獲取到a標籤中的內容

24 a = news.select('a'

)25#把內容進行迴圈

26for a1 in

a:27

#列印出內容中href後面的內容

28print(a1['

href

'])

獲取網頁中的標題,時間,**和內容

**如下:

1

import

requests

2from bs4 import

beautifulsoup

3 newurl = "

a/237171122_162758?g=0?code=96866857093125675042cacc48b055b9&_f=index_cpc_1

"4 res =requests.get(newurl)

5 res.encoding="

utf-8

"6 soup = beautifulsoup(res.text,"

html.parser")

7 title = soup.select('

.text-title

')[0].select('h1'

)[0].text

8 time = soup.select('

.article-info

')[0].select('

.time

')[0].text

9 laiyuan = soup.select('

.article-info

')[0].select('a'

)[0].text

10 content = soup.select("

.article

")[0].select('p'

)11#print("content:"+content)

12for content1 in

content:13#

這樣出來的是帶有html標籤的,這樣放到前台文字外掛程式裡面會保留在網頁上的格式,如果想去除標籤變成content1.text就好了

14print(content1)

python爬取學校新聞

這是我做的第乙個python爬蟲專案,在這裡與大家分享出來 目標 下面展示一下我的 import requests from bs4 import beautifulsoup sessions requests.session i 1 對應第1頁資訊 page str i if i 1 newsma...

Python 對新聞的爬取

今天接了乙個python小指令碼,發來一起分享。要求 廢話不說,直接上 import os import requests from lxml import etree from bs4 import beautifulsoup import re import urllib.request 獲取原...

爬取校園新聞首頁的新聞

1.用requests庫和beautifulsoup庫,爬取校園新聞首頁新聞的標題 鏈結 正文 show info。2.分析info字串,獲取每篇新聞的發布時間,作者,攝影等資訊。import requests newsurl res requests.get newsurl 返回response物...