python爬取新浪新闻首页_python3爬虫-爬取新浪新闻首页所有新闻标题

准备工作:安装requests和BeautifulSoup4。打开cmd,输入如下命令

pip install requests

pip install BeautifulSoup4

按F12打开开发人员工具,点击左上角的图片,然后再页面中点击你想查看的元素:

image_1b9cn3qf33l8r6s1skf1duh1ann9.png

我点击了新闻标题处的元素,查看到该元素为class=news-item的元素:

image_1b9cn61ap1qc62f57l5isu60m.png

在这里,我们要获取新闻的时间,标题和链接,查看到分别在如下位置:

image_1b9cnc13h1es5tc31iif1a261adr13.png

现在,就可以根据元素的结构编写爬虫代码了:

import requests

from bs4 import BeautifulSoup

url = 'http://news.sina.com.cn/china/'

res = requests.get(url)

# 使用UTF-8编码

res.encoding = 'UTF-8'

# 使用剖析器为html.parser

soup = BeautifulSoup(res.text, 'html.parser')

#遍历每一个class=news-item的节点

for news in soup.select('.news-item'):

h2 = news.select('h2')

#只选择长度大于0的结果

if len(h2) > 0:

#新闻时间

time = news.select('.time')[0].text

#新闻标题

title = h2[0].text

#新闻链接

href = h2[0].select('a')[0]['href']

#打印

print(time, title, href)

运行程序,结果如下图所示:

image_1b9cndiud9cs1oleisart8hb61g.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值