抓取网页新闻(Web·简介())
优采云 发布时间: 2021-12-09 09:07抓取网页新闻(Web·简介())
栏目:网络·
介绍本文文章主要介绍使用BeautifulSoup抓取新浪网新闻内容及相关经验技巧。文章约3967字,浏览量314,点赞4,值得参考!
第一次写小爬虫。Python确实很强大。二十行代码抓取内容并将其存储为 txt 文本。
直接编码
#coding = ‘utf-8‘
import requests
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
#抓取web页面
url = "http://news.sina.com.cn/china/"
res = requests.get(url)
res.encoding = ‘utf-8‘
#放进soup里面进行网页内容剖析
soup = BeautifulSoup(res.text, "html.parser")
elements = soup.select(‘.news-item‘)
#抓取需要的内容并且放入文件中
#抓取的内容有时间,内容文本,以及内容的链接
fname = "F:/asdf666.txt"
try:
f = open(fname, ‘w‘)
for element in elements:
if len(element.select(‘h2‘)) > 0:
f.write(element.select(‘.time‘)[0].text)
f.write(element.select(‘h2‘)[0].text)
f.write(element.select(‘a‘)[0][‘href‘])
f.write(‘\n\n‘)
f.close()
except Exception, e:
print e
else:
pass
finally:
pass
因为我第一次做的这个小爬虫有一个非常简单单一的功能,就是直接抓取新闻页面上的部分新闻。
然后抓取新闻的时间和超链接
然后按照新闻的顺序整合,放到一个文本文件中存储