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

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

pip install requests
pip install BeautifulSoup4

打开我们要爬取的页面,这里以新浪新闻为例,地址为:http://news.sina.com.cn/china/

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

image_1b9cn3qf33l8r6s1skf1duh1ann9.png-104.2kB

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

image_1b9cn61ap1qc62f57l5isu60m.png-288.5kB

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

image_1b9cnc13h1es5tc31iif1a261adr13.png-98.6kB

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

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-201.9kB

原文地址:https://www.cnblogs.com/zhuzhubaoya/p/6605754.html