python爬虫 根据关键字在新浪网站查询跟关键字有关的新闻条数(按照时间查询)

# -*- coding: utf-8 -*-
"""
Created on Thu May  8 09:14:13 2014

@author: lifeix
"""

import urllib2
import re
from datetime import datetime
def craw1(keyword_name, startYear):
    a = keyword_name
    print a,"\t"
    today = datetime.today()
    ye = today.year
    mon = today.month
    for year in range(startYear,ye + 1):
        month = 13
        if ye == year:
            month = mon
        for month in range(1,month):
            begintime = str(year) + "-" + "%02d"%month+"-01"
            endtime = str(year) + "-" + "%02d"%month+"-31"
            print begintime, endtime
            userMainUrl = "http://search.sina.com.cn/?time=custom&stime="+begintime+"&etime="+endtime+"&c=news&q="+a+"&sort=time&range=title"
            print userMainUrl
            req = urllib2.Request(userMainUrl)
            resp = urllib2.urlopen(req)
            respHtml = resp.read()
            urlpat = re.compile(r'<div class="l_v2">(.*?)</div>')
            match = urlpat.findall(respHtml)
            for numstr in match:
                searchnum = numstr[11:-2]
            print "searchnum=",searchnum
            
craw1('大学',2014)

Python爬虫用于搜索特定关键字的过程通常涉及到以下几个步骤: 1. **导入库**:首先需要导入一些基本库,如`requests`用于发送HTTP请求获取网页内容,`BeautifulSoup`或`lxml`用于解析HTML文档。 ```python import requests from bs4 import BeautifulSoup ``` 2. **设置URL**:确定你要抓取的网的URL,通常是搜索引擎如百度、Google等的搜索结果页面,会包含关键字。 3. **构造搜索查询**:将用户提供的关键字加入到URL的搜索参数中,比如Google的搜索API就是通过在URL中添加`q=关键词`来指定搜索内容。 4. **发送请求**:使用`requests.get()`函数向服务器发送GET请求,并获取响应内容。 ```python url = "https://www.google.com/search?q=" + keyword response = requests.get(url) ``` 5. **解析内容**:利用BeautifulSoup解析HTML文档,找到包含搜索结果的部分,提取所需信息,例如标题、链接等。 ```python soup = BeautifulSoup(response.text, 'html.parser') results = soup.find_all('div', class_='g') # 假设这个类名对应搜索结果 ``` 6. **处理数据**:遍历解析后的结果,提取出有用的信息,保存到文件或数据库中。 ```python for result in results: title = result.find('h3').text link = result.find('a')['href'] print(f'Title: {title}, Link: {link}') ``` 7. **异常处理**:记得处理可能出现的网络错误或解析错误。 注意这只是一个基础的爬虫框架,实际应用中可能需要处理反爬机制(如验证码、IP限制)、动态加载的内容、数据清洗等问题。另外,爬虫需遵守目标网的robots.txt协议,尊重版权和法律法规。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值