爬虫学习之路 - 开篇

本文介绍了Python爬虫的学习路径,包括基础知识、环境搭建和实践案例。建议初学者阅读相关文章以理解爬虫概念,学习Python基础和相关库如urllib、BeautifulSoup。文中还提到了Python环境配置,推荐使用Python 2.7.14和PyCharm,并提供了入门实践的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介

理论上来说,任何支持网络通信的语言都是可以写爬虫的,爬虫本身虽然语言关系不大,。但是,总有相对顺手、简单的。

目前来说,大多数爬虫是用后台脚本类语言写的,其中python无疑是用的最多最广的,并且页诞生了很多优秀的库和框架,如scrapy、BeautifulSoup 、pyquery、Mechanize等。

但是一般来说,搜索引擎的爬虫对爬虫的效率要求更高,会选用c++、java、go(适合高并发),因为我们的目标不是搜索引擎,因此我选用python来学些爬虫。

学习之路如下可以参考下面的步骤

基础:

  1. 了解爬虫
  2. 学习Python基本语法,并熟练使用
  3. 学习Python中关于爬虫的几个重要的内置库:urllib/http/Cookie等
  4. 学习正则表达式,beautifulsoup等解析网页的工具或包
  5. 利用上几步学习的至少爬取比较简单的网站,比如一些应用市场等等,不需要登陆
  6. 利用大型的框架爬取数据,例如PySpider等

高级:

  1. 学习利用工具分析网页请求流程、学习模拟登陆,拿新浪微博、知乎等需要登陆的网站进行练习
  2. 学习Python中关于多线程、多进程的东西,将以前写的代码改为多线程版本,提高效率
  3. 学习Python中的爬虫框架,或者自己写一个爬虫框架。 更高级的,还有验证码识别、js动态请求、js执行、代理IP等等。

接下来介绍其中实践过的几项

了解爬虫

爬虫简单的理解:通过程序模拟人操作网络发送请求,获取数据返回,清洗,筛选,整理出有用的数据,结构化保存数据,方便数据的浏览,计算,可视化,最终实现数字的描述型价值与预测型价值

把下面三篇文章读完,就有基本的概念了:

技术准备:Python基础

python 基础是学习python爬虫不可少的,python基础学习资源:

Blog语法和类的部分开完就可以先继续了

环境搭建

我这里使用的是:

python 2.7.14 + PyCharm

python安装时,主要要勾选pip(用于后面的各种库的安装pip install,类似于RN的npm install)

截止写blog起,PyCharm还可以用这里的方法破解

入门实践

先做学习下这几个入门实践code:

  1. 5分钟入门网络爬虫

    Code如下:(注意lxml,bs4, requests都是需要pip install的)

    #!/usr/local/bin/python
    # -*- coding: utf-8 -*-
    
    # learn from 5分钟入门网络爬虫 https://zhuanlan.zhihu.com/p/29433134
    
    import requests
    from bs4 import BeautifulSoup  # 从bs4这个库中导入BeautifulSoup
    from lxml import etree
    import sys
    
    
    def main():
        reload(sys)
        sys.setdefaultencoding('utf-8')
    
        # init
        link = "http://www.santostang.com/"
        # 用requests的headers可以伪装成浏览器访问
        headers = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}
        r = requests.get(link, headers=headers)
    
        # analysis data
        soup = BeautifulSoup(r.text, "lxml")  # 使用BeautifulSoup解析这段代码
        title = soup.find("h1", class_="post-title").a.text.strip()
        print (title)
    
        # why this way doesn't work?
        # s = etree.HTML(r.text)
        # title = s.to.xpath('//*[@id="main"]/div/div[1]/article[1]/header/h1/a/text()')
        # print (title)
    
        # write to file
        with open('title.txt', "a+") as f:
            f.write(title)
            f.close()
    
    
    if __name__ == '__main__':
        main()
    
  2. Python爬虫入门三之Urllib库的基本使用

    Code:

    #!/usr/local/bin/python
    # -*- coding: utf-8 -*-
    # learn from Python爬虫入门三之Urllib库的基本使用 http://cuiqingcai.com/947.html
    
    import sys
    import urllib2
    
    
    def main():
        reload(sys)
        sys.setdefaultencoding('utf-8')
    
        request = urllib2.Request("http://www.baidu.com")
        response = urllib2.urlopen(request)
        print response.read()
    
    
    if __name__ == '__main__':
        main()
    
  3. 爬取豌豆及某个app的数据

    # coding=utf-8
    # !/usr/bin/python
    
    # pa zentalk cn store data from wandoujia, with requests + bs4
    
    import sys
    import requests
    from bs4 import BeautifulSoup  # 从bs4这个库中导入BeautifulSoup
    import tool
    import time
    
    FILE_NAME = 'zentalk_test.txt'
    
    
        class WandoujiaSpider:
            def __init__(self):
                self.tool = tool.Tool()
                reload(sys)
                sys.setdefaultencoding('utf-8')
    
            # 获取当前时间
            def getCurrentDate(self):
                return time.strftime('%Y-%m-%d', time.localtime(time.time()))
    
            # 获取当前时间
            def getCurrentTime(self):
                return time.strftime('[%Y-%m-%d %H:%M:%S]', time.localtime(time.time()))
    
            def requestData(self, url, headers):
                r = requests.get(url, headers=headers)
                return r
    
            def analysisData(self, html):
                # analysis data
                soup = BeautifulSoup(html.text, "lxml")  # 使用BeautifulSoup解析这段代码
    
                # analysis data
                title = soup.find("p", class_="app-name").span.get_text()
                installtext = soup.find("span", class_="item install").i.get_text()
                install = self.tool.getCount(installtext)
                good_eval = soup.find("span", class_="item love").i.get_text()
                infos = soup.find("dl", class_="infos-list").find_all("dd")
                size = self.tool.replace(infos[0].get_text())
                update = self.tool.replace(infos[3].get_text())
                version = self.tool.replace(infos[4].get_text())
                upload = self.tool.replace(infos[6].get_text())
    
                result = {}
                result["title"] = title
                result["size"] = size
                result["update"] = update
                result["version"] = version
                result["upload"] = upload
                result["install"] = install
                result["good_eval"] = good_eval
    
                # get comments
                comments = soup.find("ul", class_="comments-list").find_all("li")
                if (len(comments) - 1 > 0):
                    result["comment_count"] = len(comments) - 1
                    cinfos = []
                    for item in comments:
                        pitems = item.find_all("p")
                        if (len(pitems) > 0):
                            cinfo = {}
                            nitems = pitems[0].find_all("span")
                            cinfo["user"] = nitems[0].get_text()
                            cinfo["comment_time"] = nitems[1].get_text()
                            cinfo["comment_des"] = pitems[1].span.get_text()
                            cinfos.append(cinfo)
                    result["comments"] = cinfos
    
                return result
    
            def start(self, url=None, headers=None):
                if not url:
                    url = "http://www.wandoujia.com/apps/com.asus.cnzentalk"
                    # 用requests的headers可以伪装成浏览器访问
                    headers = {
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'}
    
                html = self.requestData(url, headers)
                data_dist = self.analysisData(html)
                return data_dist
    
            def saveData(self, dict, des):
                # write to file
                f = open(FILE_NAME, 'w')
                f.write("title: " + dict["title"] + '\n')
                f.write("size: " + dict["size"] + '\n')
                f.write("update: " + dict["update"] + '\n')
                f.write("version: " + dict["version"] + '\n')
                f.write("upload: " + dict["upload"] + '\n')
                f.write("install: " + str(dict["install"]) + '\n')
                f.write("好评率: " + dict["good_eval"] + '\n\n')
                # write comments
                if (dict.has_key("comments")):
                    comments = dict["comments"]
                    if (len(comments) > 0):
                        f.write("用户评论数: " + str(dict["comment_count"]) + '\n')
                        for item in comments:
                            f.write("评论者: " + item["user"] + '\n')
                            f.write("评论时间: " + item["comment_time"] + '\n')
                            f.write("评论: " + item["comment_des"] + '\n')
                f.close()
    
            def readData(self):
                with open(FILE_NAME, 'r') as f:
                    print f.read()
                    f.close()
    
    
        wandoujia = WandoujiaSpider()
        wandoujia.saveData(wandoujia.start(), "wandoujia")
        wandoujia.readData()
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值