python2.7 爬虫初体验爬取新浪国内新闻_20161130

python2.7 爬虫初学习

模块:BeautifulSoup requests

1、获取新浪国内新闻标题

2、获取新闻url

3、还没想好,想法是把第2步的url 获取到下载网页源代码 再去分析源代码 获取新闻详情页 发表时间 新闻来源等数据 结合MySQLdb模块导入到数据库

4、疑惑:期望是整体获取这些字段 发表时间 发布标题 新闻详情内容 新闻来源 

任重而道远。。都想拜个老师带带了。。

#coding:utf-8
import requests
from bs4 import BeautifulSoup as bs

url='http://news.sina.com.cn/china/'
res=requests.get(url)
res.encoding='utf-8'
html=res.text
soup=bs(html,'html.parser')
title=soup.select('.blk12')[0].text
print title
t=soup.select('.blk12 a')
for i in range(len(t)):
    url=t[i]['href']
    #print url
    res = requests.get(url)
    res.encoding = 'utf-8'
    html = res.text
    soup = bs(html, 'html.parser')
    #还没循环    
    news_title = soup.select('#artibodyTitle')[0].text
    news_time=soup.select('.time-source')[0].contents[0].strip()
    news_source=soup.select('.time-source span a')[0].text
    print news_title,news_time,news_source

  

原文地址:https://www.cnblogs.com/Mr-Cxy/p/6119862.html