我的第一个Python爬虫

参考了晚上很多资料

就是抓取http://m.i21st.cn/speaking/oraltraining_1.html这个网站上的英语资料 ,没事练练英语~哈哈~


# -*- coding: utf-8 -*-
import urllib2
import urllib
import re
import thread
import time


class HTML_Model:  
      
    def __init__(self):  
        self.page = 1  
        self.pages = []  
       #self.myTool = HTML_Tool()  
        self.enable = False  
        
  
    def GetPage(self,page):  
        myUrl = "http://m.i21st.cn/speaking/oraltraining_" + page +".html"
        myResponse  = urllib2.urlopen(myUrl)  
        myPage = myResponse.read()  
        #encode的作用是将unicode编码转换成其他编码的字符串  
        #decode的作用是将其他编码的字符串转换成unicode编码  
        unicodePage = myPage.decode("utf-8")  
                
        # 找出所有class="content"的div标记  
        #re.S是任意匹配模式,也就是.可以匹配换行符  
        myItems = re.findall("</div><a.*?href='(.*?)'.*?class='h3'>(.*?)</a>",unicodePage,re.S)  
      
        items = []  
        for item in myItems:    
            items.append([item[0].replace("\n",""),item[1].replace("\n","")])  
        return items  
  
    


      
    def LoadPage(self):  
        
        while self.enable:  
            
            if len(self.pages) < 2:  
                try:  
                      
                    myPage = self.GetPage(str(self.page))  
                    self.page += 1  
                    self.pages.append(myPage)  
                except:  
                    print '无法显示新的资料!'  
            else:  
                time.sleep(1)  
           
    def ShowPage(self,q,page):  
        for items in q:  
            print u'第%d页' % page , items[1]  
            #——————————————————————
            myUrl = "http://m.i21st.cn" + str(items[0])
            myResponse  = urllib2.urlopen(myUrl)  
            myPage = myResponse.read()  
            #encode的作用是将unicode编码转换成其他编码的字符串  
            #decode的作用是将其他编码的字符串转换成unicode编码  
            unicodePage = myPage.decode("utf-8")
            #myItems = re.findall("</div><a.*?href='(.*?)'.*?class='h3'>(.*?)</a>",unicodePage,re.S)
            temp = re.findall("<a.*?id='contentbegin'.*?name='contentbegin'></a>(.*?)</div>",unicodePage,re.S)
            
            temp1=temp[0].encode("utf-8")
           
            temp2=re.findall("<br.*?/>(.*?)</p>",temp1,re.S)
           
            temp3=temp2[0].decode("utf-8")
           
            #myItems = re.findall("<br.*?/>[\n](.*?)<br.*?/>(.*?)",temp1,re.S)
            
            
            temp4 =str(temp3.encode("gbk"))
            
            temp4=temp4.replace("'","")
            temp4=temp4.replace("<br />","")
            temp4=temp4.replace("<strong>","")
            temp4=temp4.replace("</strong>","")
            temp4=temp4.replace("&rsquo","")
            temp4=temp4.replace("&ldquo","")
            temp4=temp4.replace("&rdquo","")
            text=temp4.replace(";","'")


            #————————————————————————————————————————
          # print self.myTool.Replace_Char(items[1])
            print text  
            myInput = raw_input()  
            if myInput == "quit":  
                self.enable = False  
                break  
           
    def Start(self):  
        self.enable = True  
        page = self.page  
   
        print u'正在加载中请稍候......'  
           
        # 新建一个线程在后台加载段子并存储  
        thread.start_new_thread(self.LoadPage,())  
           
       
        while self.enable:  
            
            if self.pages:  
                nowPage = self.pages[0]  
                del self.pages[0]  
                self.ShowPage(nowPage,page)  
                page += 1  
   
   
#----------- 程序的入口处 -----------  
print u""" 
--------------------------------------- 
   程序:英语学习—爬虫
   语言:Python2.7
   作者:xiantian
   功能:按下回车依次浏览今日的英语资料 
--------------------------------------- 
"""  
   
   
print u'请按下回车浏览今日新的内容:'  
raw_input(' ')  
myModel = HTML_Model()  
myModel.Start()  


创建一个简单的Python爬虫框架,我们可以使用`requests`和`BeautifulSoup`这两个库。下面将指导您构建这样一个基本框架。 ### 第一步:安装必要的库 首先,你需要在你的环境中安装`requests` 和 `beautifulsoup4`。你可以使用pip命令安装它们: ```bash pip install requests beautifulsoup4 ``` ### 第二步:设计框架结构 我们定义一个基础的爬虫类,这个类会封装请求网页、解析HTML以及存储数据的功能。 #### 类结构说明: 1. **初始化方法** (`__init__`):设置默认参数,比如超时时间、请求头部信息等。 2. **获取网页源码** (`get_html(url)`):发送HTTP GET请求并返回响应的内容。 3. **解析HTML** (`parse_html(html_content)`):使用BeautifulSoup解析HTML内容,提取有用的数据。 4. **存储数据** (`store_data(data)`):根据需求将数据保存到文件或其他数据库。 ### 实现代码 ```python import requests from bs4 import BeautifulSoup class SimpleSpider: def __init__(self, timeout=5, headers={'User-Agent': 'Mozilla/5.0'}): self.timeout = timeout self.headers = headers def get_html(self, url): try: response = requests.get(url, headers=self.headers, timeout=self.timeout) if response.status_code == 200: return response.text else: print(f"Failed to get the HTML content with status code {response.status_code}") return None except Exception as e: print(f"Error occurred while getting the HTML content: {e}") return None def parse_html(self, html_content): soup = BeautifulSoup(html_content, "html.parser") # 这里假设页面有一个特定的标签用于抓取数据,例如所有链接 links = [a['href'] for a in soup.find_all('a')] return links def store_data(self, data): filename = "data.txt" with open(filename, 'w') as file: for item in data: file.write("%s\n" % item) # 使用示例 spider = SimpleSpider() url = "https://example.com" # 目标网站URL content = spider.get_html(url) if content is not None: parsed_data = spider.parse_html(content) spider.store_data(parsed_data) else: print("Could not fetch and process the HTML content.") ``` ### 注意事项: - 确保遵守目标网站的`robots.txt`规则和版权法律。 - 对于更复杂的爬虫,你可能还需要处理JavaScript渲染的页面、登录认证等问题。 - 考虑使用异步请求来提高速度,可以使用`asyncio`和`aiohttp`库。 以上就是一个基础的Python爬虫框架的实现,您可以根据实际需求调整和扩展功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值