python爬取网页新闻_Python爬取新闻网数据
前言
本文的文字及圖片來源于網(wǎng)絡(luò),僅供學(xué)習(xí)、交流使用,不具有任何商業(yè)用途,如有問題請及時聯(lián)系我們以作處理。
PS:如有需要Python學(xué)習(xí)資料的小伙伴可以加點(diǎn)擊下方鏈接自行獲取
基本開發(fā)環(huán)境
Python 3.6
Pycharm
import parsel
import requests
import re
目標(biāo)網(wǎng)頁分析
今天就爬取新聞網(wǎng)中的國際新聞欄目
點(diǎn)擊顯示更多新聞內(nèi)容
可以看到相關(guān)的數(shù)據(jù)接口,里面有新聞標(biāo)題以及新聞詳情的url地址
如何提取url地址
1、轉(zhuǎn)成json,鍵值對取值;
2、用正則表達(dá)式匹配url地址;
兩種方法都可以實現(xiàn),看個人喜好
根據(jù)接口數(shù)據(jù)鏈接中的pager 變化進(jìn)行翻頁,其對應(yīng)的就是頁碼。
詳情頁可以看到新聞內(nèi)容都是在 div標(biāo)簽里面 p 標(biāo)簽內(nèi),按照正常的解析網(wǎng)站即可獲取新聞內(nèi)容。
保存方式
1、你可以保存txt文本形式
2、也可以保存成PDF形式
之前也講過關(guān)于爬取文章內(nèi)容保存成 PDF ,可以點(diǎn)擊下方鏈接查看相關(guān)保存方式。
本篇文章的話,就使用保存txt文本的形式吧。
整體爬取思路總結(jié)
在欄目列表頁中,點(diǎn)擊更多新聞內(nèi)容,獲取接口數(shù)據(jù)url
接口數(shù)據(jù)url中返回的數(shù)據(jù)內(nèi)容中匹配新聞詳情頁url
使用常規(guī)解析網(wǎng)站操作(re、css、xpath)提取新聞內(nèi)容
保存數(shù)據(jù)
代碼實現(xiàn)
獲取網(wǎng)頁源代碼
def get_html(html_url):
"""
獲取網(wǎng)頁源代碼 response
:param html_url: 網(wǎng)頁url地址
:return: 網(wǎng)頁源代碼
"""
response = requests.get(url=html_url, headers=headers)
return response
獲取每篇新聞url地址
def get_page_url(html_data):
"""
獲取每篇新聞url地址
:param html_data: response.text
:return: 每篇新聞的url地址
"""
page_url_list = re.findall('"url":"(.*?)"', html_data)
return page_url_list
文件保存命名不能含有特殊字符,需要對新聞標(biāo)題進(jìn)行處理
def file_name(name):
"""
文件命名不能攜帶 特殊字符
:param name: 新聞標(biāo)題
:return: 無特殊字符的標(biāo)題
"""
replace = re.compile(r'[\\\/\:\*\?\"\\|]')
new_name = re.sub(replace, '_', name)
return new_name
保存數(shù)據(jù)
def download(content, title):
"""
with open 保存新聞內(nèi)容 txt
:param content: 新聞內(nèi)容
:param title: 新聞標(biāo)題
:return:
"""
path = '新聞\\' + title + '.txt'
with open(path, mode='a', encoding='utf-8') as f:
f.write(content)
print('正在保存', title)
主函數(shù)
def main(url):
"""
主函數(shù)
:param url: 新聞列表頁 url地址
:return:
"""
html_data = get_html(url).text # 獲得接口數(shù)據(jù)response.text
lis = get_page_url(html_data) # 獲得新聞url地址列表
for li in lis:
page_data = get_html(li).content.decode('utf-8', 'ignore') # 新聞詳情頁 response.text
selector = parsel.Selector(page_data)
title = re.findall('
(.*?)', page_data, re.S)[0] # 獲取新聞標(biāo)題new_title = file_name(title)
new_data = selector.css('#cont_1_1_2 div.left_zw p::text').getall()
content = ''.join(new_data)
download(content, new_title)
if __name__ == '__main__':
for page in range(1, 101):
url_1 = 'https://channel.chinanews.com/cns/cjs/gj.shtml?pager={}&pagenum=9&t=5_58'.format(page)
main(url_1)
運(yùn)行效果圖
總結(jié)
以上是生活随笔為你收集整理的python爬取网页新闻_Python爬取新闻网数据的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 配置tomcat_Tomcat 配置必备
- 下一篇: websocket python爬虫_p