Python获取新闻内容

获取新浪新闻的新闻内容

因为新浪新闻里的新闻是放置在p标签内的,所以获取P标签的内容,


import urllib.request  
import re   
from bs4 import BeautifulSoup  
from distutils.filelist import findall  
  #浏览地址,获取html内容
url='https://news.sina.com.cn/gov/xlxw/2019-12-06/doc-iihnzhfz3978738.shtml'
headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0'}
page1=urllib.request.Request(url,headers=headers)
page=urllib.request.urlopen(page1)
contents = page.read()   
soup = BeautifulSoup(contents,"html.parser")  
list=[]#保存数据的数组
for t  in soup.find_all('p'):  # for循环遍历所有p标签,并把返回列表中的内容赋给t
    print(t.get_text().strip("").strip('\r\n').replace(u'\u3000', u' ').replace(u'\xa0', u' ')+"\n")#去特殊符号
    list.append( t.get_text().strip("").strip('\r\n').replace(u'\u3000', u' ').replace(u'\xa0', u' '))    #去特殊符号  
file=open('data.txt','w',encoding='UTF-8-sig')#保存为txt
file.write(str(list)); ""
file.close()  

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值