生活随笔
收集整理的這篇文章主要介紹了
爬取新浪新闻网
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
爬取新聞的標題,日期和鏈接
import requests
from bs4
import BeautifulSoupurl=
'http://news.sina.com.cn/china/'
res=requests.get(url)
soup=BeautifulSoup(res.text,
'lxml')
print(soup)
此時會發現爬取的數據中中文全部為亂碼,因此應加入一句:
res.encoding=
'utf-8'
而新聞標題,時間和鏈接都放在.new-item下,我們查詢new-item并輸出
在寫select()里面內容的時候標簽名不加任何修飾,類名class前加點,id名前加 #
import requests
from bs4
import BeautifulSoupurl=
'http://news.sina.com.cn/china/'
res=requests.get(url)
res.encoding=
'utf-8'
soup=BeautifulSoup(res.text,
'lxml')
for news
in soup.select(
'.news-item'):print(news)
輸出:
此時我們可以發現,標題在h2標簽下,時間在time下,鏈接在a標簽下
import requests
from bs4 import BeautifulSoupurl=
'http://news.sina.com.cn/china/'
res=requests.
get(url)
res.encoding=
'utf-8'
soup=BeautifulSoup(res.
text,
'lxml')
for news
in soup.select(
'.news-item'):
if len(news.select(
'h2'))>
0:title=news.select(
'h2')[
0].
text a=news.select(
'a')[
0][
'href']
time=news.select(
'.time')[
0].
text print(
time)print(title)print(
a)print
輸出結果:
隨意點開其中一個標題,我們進行爬取標題,時間來源
1.爬取標題
import requests
from bs4
import BeautifulSoupurl=
'http://news.sina.com.cn/c/nd/2017-08-03/doc-ifyitapp0298122.shtml'
res=requests.get(url)
res.encoding=
'utf-8'
soup=BeautifulSoup(res.text,
'html.parser')title=soup.select(
'#artibodyTitle')[
0].text
print(title)
對于title=soup.select(‘#artibodyTitle’)[0].text title的類型是list,標題只有一個,因此list中只有一個元素,因此用[0]來取第一個元素
2.爬取時間和文章來源
時間和來源都在class=”time-source”下
time=soup.
select(
'.time-source')[
0].text
print(
time)
此時我們取得了時間和文章來源,都在在列表下第一個元素中,但如果我們想要將時間和來源分別單獨取出
<span class="time-source" id="navtimeSource">2017年08月03日17:40
<span>
<span data-sudaclick="media_name"><a href="http://app.peopleapp.com/Api/600/DetailApi/shareArticle?type=0&article_id=669164" rel="nofollow" target="_blank">新浪綜合
</a></span></span>
</span>
可見時間在一個span下,而文章來源也包括在一個span下,因此
可在select后加.content就會將它們分為一個列表中的兩個元素
time=soup.
select(
'.time-source')[
0].contents
print (
time)
可見到圖片中逗號,有兩個元素
取第一個元素時間:
time=soup.
select(
'.time-source')[
0].contents[
0]
print (
time)
取第二個元素文章來源:
time=soup.
select(
'.time-source')[
0].contents[
1].text
print (
time)
3.爬取文章內容
article=soup.
select(
'#artibody p')
print (article)
文章在id=artibody下,我們同時可以發現每一段文章都在一對p標簽中間,因此加個p,得到
加入我們不想要最后一句話“責任編輯:張迪”這句話,只需:
article=soup.
select(
'#artibody p')[:-
1]
print (article)
輸出所有文字:
article=soup.
select(
'#artibody')[
0].
text
print(article)
4.爬取文章的評論數量
command=soup.select('#commentCount1')
print(
command)
此時我們輸出時發現并未顯示評論數量
評論是透過JavaScript的方式加載到網頁上的,因此我們要找到相應的JavaScript
我們在JS下面找到了204,展開后發現評論者的評論
此時我們點擊headers,復制url下的鏈接來抓取評論
總結
以上是生活随笔為你收集整理的爬取新浪新闻网的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。