简单爬虫--爬取百度热点新闻标题

1.查看网页源代码

打开百度新闻网页,link,F12,打开查看代码:
在这里插入图片描述

1.1复制头条新闻源代码

点击左上角的图标(蓝色),然后将鼠标移到第一条新闻标题上:
在这里插入图片描述鼠标右键,复制代码:
在这里插入图片描述
粘贴的结果是:#pane-news > div > ul > li.hdline0 > strong > a
鼠标移到第二个标题,并复制代码得到的结果为:#pane-news > div > ul > li.hdline1 > strong > a > b
第三个标题:#pane-news > ul:nth-child(2) > li.bold-item > a:nth-child(2)
相信你应该已经发现,除了最上面的头条外(强调:属于第一个紧挨着的头条,有时候只有一个,为 li.hdline0,有时候多个就是 li.hdline0和 li.hdline1…)选择器中 li.hdline+数字,其余几个选择器都是只有 ul:nth-child() 括号中的数字不同,所以除了第一题目,其余标题可以使用 ul:nth-child(n) 提取出来。

2.编写程序

from requests_html import HTMLSession#一个与requests库不同的新库,大家可以尝试学习一下
session = HTMLSession()
def get_news(url):#定义一个函数
    news_titles = []#定义一个空集合
    r = session.get(url)#获得页面信息
    title_baidu1 = r.html.find('#pane-news > div > ul > li.hdline0 > strong > a', first=True)#上文强调过,有时候最上面有俩个头条,可以加如下代码
    #title_baidu1 = r.html.find('#pane-news > div > ul > li.hdline1 > strong > a', first=True)#只是li.hdline1不同
    news_titles.append(title_baidu1.text)
    title_baidu3 = r.html.find('#pane-news > ul:nth-child(n) > li.bold-item > a')#这是一个列表的形式
    for title in title_baidu3:
        news_titles.append(title.text)
    for title in news_titles:
        print(title)
url = 'https://news.baidu.com/'
if __name__=='__main__':
    get_news(url)

3.运行结果

在这里插入图片描述

爬取百度新闻的热点要闻通常涉及到网络爬虫技术,可以使用Python库如BeautifulSoup和requests配合实现。以下是一个简化版的步骤: 1. **安装必要的库**: 首先需要安装`requests`库用于发送HTTP请求,以及`beautifulsoup4`库用于解析HTML内容。如果你还没有安装,可以在命令行中运行: ``` pip install requests beautifulsoup4 ``` 2. **编写爬虫脚本**: 使用Python编写一个函数,通过URL访问百度新闻首页,然后解析出热门新闻的链接和标题。例如: ```python import requests from bs4 import BeautifulSoup def get_hot_news(url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 找到新闻列表并提取相关信息 news_list = soup.select('.hotnews li a') # 根据实际HTML结构调整选择器 for news in news_list: title = news.text.strip() link = news['href'] save_to_db(title, link) # 将数据保存到数据库 def save_to_db(title, link): # 这里只是一个示例,你需要替换为实际的数据持久化操作,比如SQLite、MySQL等 with open('news_data.txt', 'a') as f: f.write(f'{title}\t{link}\n') # 调用函数获取和保存数据 get_hot_news("https://news.baidu.com/") ``` 3. **数据持久化**: 在`save_to_db`函数中,我们暂时使用了文本文件`news_data.txt`来保存数据。实际上,应该考虑使用数据库系统进行持久化,以便查询和管理。 注意:爬取网站时请遵守网站的robots.txt规则,并尊重版权。频繁大量地爬取可能会被视为滥用,有可能导致IP被封禁。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值