爬取所有校园新闻

本文介绍了一个使用Python爬取校园新闻的实例,通过requests和BeautifulSoup实现了新闻标题、链接、发布时间、来源及点击次数等信息的抓取。文章还展示了如何遍历多页新闻列表并获取每条新闻的详细内容。

1.获取单条新闻的#标题#链接#时间#来源#内容 #点击次数,并包装成一个函数。

复制代码
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
url='http://news.gzcc.cn/html/xiaoyuanxinwen/'
res=requests.get(url)
res.encoding='utf-8'   
soup=BeautifulSoup(res.text,'html.parser')
 
for news in soup.select('li'):
    if len(news.select('.news-list-title'))>0:
        title=news.select('.news-list-title')[0].text
        url=news.select('a')[0]['href']
        time=news.select('.news-list-info')[0].contents[0].text
        dt=datetime.strptime(time,'%Y-%m-%d')                           
        source=news.select('.news-list-info')[0].contents[1].text
        
        print(title,url,time,dt,source)
复制代码

2.获取一个新闻列表页的所有新闻的上述详情,并包装成一个函数。

复制代码
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
url='http://news.gzcc.cn/html/xiaoyuanxinwen/'
res=requests.get(url)
res.encoding='utf-8'   
soup=BeautifulSoup(res.text,'html.parser')

for news in soup.select('li'):
    if len(news.select('.news-list-title'))>0:
        title=news.select('.news-list-title')[0].text
        url=news.select('a')[0]['href']
        time=news.select('.news-list-info')[0].contents[0].text
        dt=datetime.strptime(time,'%Y-%m-%d')                           
        source=news.select('.news-list-info')[0].contents[1].text
        
        resd=requests.get(url)
        resd.encoding='utf-8'
        soupd=BeautifulSoup(resd.text,'html.parser')
        ar=soupd.select('.show-content')[0].text
        print(title,url,time,dt,source,ar)
        break
复制代码

3.获取所有新闻列表页的网址,调用上述函数。

复制代码
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
url='http://news.gzcc.cn/html/xiaoyuanxinwen/'
res=requests.get(url)
res.encoding='utf-8'   
soup=BeautifulSoup(res.text,'html.parser')

        


def getonepage(listurl):
    res=requests.get(listurl)
    res.encoding='utf-8'   
    soup=BeautifulSoup(res.text,'html.parser')

    
for news in soup.select('li'):
    if len(news.select('.news-list-title'))>0:
        title=news.select('.news-list-title')[0].text
        url=news.select('a')[0]['href']
        time=news.select('.news-list-info')[0].contents[0].text
        dt=datetime.strptime(time,'%Y-%m-%d')                           
        source=news.select('.news-list-info')[0].contents[1].text
        
        resd=requests.get(url)
        resd.encoding='utf-8'
        soupd=BeautifulSoup(resd.text,'html.parser')
        ar=soupd.select('.show-content')[0].text

        print(title,url,time,dt,source)

getonepage('http://news.gzcc.cn/html/xiaoyuanxinwen/index.html')
res.encoding='utf-8'   
soup=BeautifulSoup(res.text,'html.parser')
page= int(soup.select('.a1')[0].text.rstrip('条'))//10+1
for i in range(2,page+1):
    listurl='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
    getonepage(listurl)
复制代码

 

4.完成所有校园新闻的爬取工作。

复制代码
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
url='http://news.gzcc.cn/html/xiaoyuanxinwen/'
res=requests.get(url)
res.encoding='utf-8'   
soup=BeautifulSoup(res.text,'html.parser')

        

def getclick(newurl):
    id = re.match('http://news.gzcc.cn/html/2017/xiaoyuanxinwen_(.*).html',newurl).groups()[0].split('/')[1]
    clickurl = 'http://oa.gzcc.cn/api.php?op=count&id=8301&modelid=80'.format(id)
    click = int(requests.get(clickurl).text.split('.')[-1].lstrip("html('").rstrip("');"))
    return(click)

def getonepage(listurl):
    res=requests.get(listurl)
    res.encoding='utf-8'   
    soup=BeautifulSoup(res.text,'html.parser')

    
for news in soup.select('li'):
    if len(news.select('.news-list-title'))>0:
        title=news.select('.news-list-title')[0].text
        url=news.select('a')[0]['href']
        time=news.select('.news-list-info')[0].contents[0].text
        dt=datetime.strptime(time,'%Y-%m-%d')                           
        source=news.select('.news-list-info')[0].contents[1].text
        
        resd=requests.get(url)
        resd.encoding='utf-8'
        soupd=BeautifulSoup(resd.text,'html.parser')
        ar=soupd.select('.show-content')[0].text

        click=getclick(url)
        print(title,url,time,dt,source,click)

getonepage('http://news.gzcc.cn/html/xiaoyuanxinwen/index.html')
res.encoding='utf-8'   
soup=BeautifulSoup(res.text,'html.parser')
page= int(soup.select('.a1')[0].text.rstrip('条'))//10+1
for i in range(2,4):
    listurl='http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
    getonepage(listurl)
复制代码

转载于:https://www.cnblogs.com/zcr123/p/7657357.html

### 如何使用爬虫技术抓取学校官网新闻数据 #### 1. 确定目标站的结构 在开始编写爬虫之前,需要分析目标站(如学校官网)的HTML结构。通过浏览器的开发者工具(通常是F12快捷键),可以查看新闻页面的HTML代码,找到新闻标题、发布时间、正文等内容的具体标签和属性[^1]。 #### 2. 使用合适的编程语言和库 Python是实现络爬虫的常用语言,因为它提供了丰富的第三方库来简化开发过程。以下是常用的库: - `requests`:用于发送HTTP请求。 - `BeautifulSoup` 或 `lxml`:解析HTML文档并提取所需信息。 - `pandas`:处理和存储抓取的数据。 - `selenium`:如果页内容是动态加载的,可以使用Selenium模拟浏览器行为[^2]。 #### 3. 编写爬虫代码 以下是一个简单的示例代码,展示如何抓取学校官网新闻的基本信息: ```python import requests from bs4 import BeautifulSoup # 发送HTTP请求获取页内容 url = "https://example.school.edu/news" # 替换为实际的学校官网新闻URL headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" } response = requests.get(url, headers=headers) # 解析HTML文档 soup = BeautifulSoup(response.text, 'html.parser') # 提取新闻标题、链接和其他相关信息 news_items = soup.find_all('div', class_='news-item') # 替换为实际的新闻容器类名 for item in news_items: title = item.find('h2').text.strip() # 新闻标题 link = item.find('a')['href'] # 新闻链接 date = item.find('span', class_='date').text.strip() # 发布时间 print(f"标题: {title}\n链接: {link}\n日期: {date}\n") ``` 上述代码中,关键部分包括发送请求、解析HTML以及提取特定标签的内容。需要注意的是,实际的HTML结构可能有所不同,因此需要根据具体情况进行调整[^3]。 #### 4. 处理动态加载的页 如果学校新闻页面是通过JavaScript动态加载的,普通的`requests`库可能无法直接获取到完整的页面内容。此时可以使用`Selenium`来模拟浏览器行为。例如: ```python from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from bs4 import BeautifulSoup # 启动Selenium WebDriver service = Service(executable_path='/path/to/chromedriver') # 替换为ChromeDriver的实际路径 driver = webdriver.Chrome(service=service) driver.get("https://example.school.edu/news") # 等待页面加载完成 driver.implicitly_wait(10) # 获取页面源代码并解析 soup = BeautifulSoup(driver.page_source, 'html.parser') news_items = soup.find_all('div', class_='news-item') for item in news_items: title = item.find('h2').text.strip() link = item.find('a')['href'] date = item.find('span', class_='date').text.strip() print(f"标题: {title}\n链接: {link}\n日期: {date}\n") # 关闭浏览器 driver.quit() ``` #### 5. 遵守法律与道德规范 在进行爬取时,必须遵守目标站的`robots.txt`文件规定以及相关法律法规。此外,频繁地访问站可能会对服务器造成负担,因此建议设置合理的请求间隔时间,避免被封禁IP地址[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值