import requests
from bs4import BeautifulSoup
import pymongo
url ='http://news.sina.com.cn/china/'
res = requests.get(url)# 使用get方法请求url
res.encoding ='utf-8' # 将编码格式设置为utf-8
soup = BeautifulSoup(res.text, 'html.parser')
client = pymongo.MongoClient('localhost', 27017)# 创建连接,因为用的本机的mongodb数据库,所以直接写localhost即可,也可以写成127.0.0.1,27017为端口
db = client['mydb']# 连接的数据库
collection = db['my_collection']# 连接的表
for newsin soup.select('.news-item'):#查找出class内容含news-item的,并使用循环遍历每一个
if len(news.select('h2')) >0 :# 判断标题是否为空,不为空时做详细处理
h2 = news.select('h2')[0].text# 获取新闻的标题,并赋值给变量h2
time = news.select('.time')[0].text# 获取标题的时间,并赋值给time
url = news.select('a')[0]['href']# 获取标题的url,并赋值给url
data = {'title': h2, 'time': time, 'url':url}# 将数据存入到字典变量data中
collection.insert(data)# 将data中的输入插入到mongodb数据库