python爬取新闻标题_python对某个页面的新闻标题和时间的爬取

#coding=utf-8

import urllib

from bs4 import

BeautifulSoup

import codecs

file1 = codecs.open('1.txt',

'w')

content =

urllib.urlopen('http://mp.weixin.qq.com/s?__biz=MTI0MDU3NDYwMQ==&mid=406948985&idx=1&sn=042190493d6a1f9b5213e53bba215e51&3rd=MzA3MDU4NTYzMw==&scene=6#rd').read()

soup =

BeautifulSoup(content)

# title =

soup.find('h2').get_text()

# titletime =

soup.find('em').get_text()

print

u'内容:'+soup.find('title').get_text() +' ' +

u'时间:'+soup.find('em').get_text()

'''

# soup

就是BeautifulSoup处理格式化后的字符串,

soup.title 得到的是title标签,

soup.p

得到的是文档中的第一个p标签,要想得到所有标签,得用find_all函数。

find_all

函数返回的是一个序列,可以对它进行循环,依次得到想到的东西

.get_text()

是返回文本,这个对每一个BeautifulSoup处理后的对象得到的标签都是生效的。

你可以试试 print

soup.p.get_text()

'''

==================================================================

# -*-coding: utf8-*-

from bs4 import BeautifulSoup as bs

import requests

url =

r'http://mp.weixin.qq.com/s?__biz=MTI0MDU3NDYwMQ==&mid=406948985&idx=1&sn=042190493d6a1f9b5213e53bba215e51&3rd=MzA3MDU4NTYzMw==&scene=6#rd'

headers = {'User-agent': 'Mozilla/5.0(compatible; MSIE 10.0;

windows NT 6.1; wow64; Trident/6.0)',

'Aceept-Encoding': 'gzip, deflate',

'Accent-Language': 'en-US, en; q=0.5',

'Connection': 'keep-alive'

}

response = requests.get(url, headers=headers)

soup = bs(response.content.decode('utf-8'), 'lxml')

title = soup('title')[0].text

time = soup('em')[0].text

print u'标题:%s\r\n时间:%s' % (title, time)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值