python爬虫(1)——基本知识和概念

    • python 基本语法
      • 加法和乘法
      • 切片索引
      • 字符串方法
    • python 爬虫原理
    • python 爬虫第三方库
      • Requests
      • BeautifulSoup
        • find、find_all
        • selector
      • Lxml

python 基本语法

python 爬虫的对象大部分都是文本,所以需要对python字符串的用法熟悉。python中字符串是由双引号或者单引号中的字符组成。通常用到的字符串操作有加法乘法、切片索引、格式化等

  • 加法和乘法

    字符串的加法在python爬虫中通常用于URL的构造

    a =  "hello"
    b = "world"
    print(a+b)# helloworld

    python对字符串的操作相对于传统语言,不同之处在于包含一个乘法。格式为字符串*number对应的乘数代表将字符串复制此数字的份数

    a = "python"
    print(a*3)# pythonpythonpython
  • 切片索引

    字符串的索引和切片是通过string[x]来获取字符串相关的信息

    a = "python"
    print(a[0]) # p
    print(a[-1])# n
    print(a[:2])# py

    字符串的索引从0开始,最后一个字符的索引也可以为-1。可以使用 : 来进切片操作。
    a[:2] 不包括下标为2的元素

  • 字符串方法

    python 中字符串除了上面的基本操作外,还提供了一系列的方法来增强其功能,方便开发者使用对其进行处理。

    • split()
      split方法会将字符串按照用户指定的分隔符进行分割,生成一个列表

      a = "123-456-789"
      print(a.split("-"))# ['123', '456', '789']

      可以看到通过调用split方法将字符串按照指定的分隔符进行了切割。

      当没有指定分隔符时,程序会默认将所有的空格作为分隔符(空格、制表符、换行等等)

    • replace()
      replace 函数其实本质上就是字符串的查找和替换,会替换用户指定的字符串到原有字符串上

      a = "pythonlinux"
      print(a.replace("linux","C++"))#pythonC++
    • strip()
      strip函数会将字符串两侧的空格去除,但是不会影响中间的空格。

      a = "  python   \n"
      print(a.strip()) #python
    • format()
      format经常用在python爬虫中,我通常用来格式化URL

      print("https://www.{}.com".format("baidu")) #https://www.baidu.com 

python 爬虫原理

对于计算机网络不熟练的我们,在学习爬虫时,只需要知道基本的网络连接原理即可,计算机发送一个Request,服务器返回一个Response。
python爬虫(1)——基本知识和概念_第1张图片
那么对于网络爬虫来说,我们只需要模拟上述过程即可,即

  • 构造访问请求头等数据,发起一个Request
  • 解析服务器端返回的Respone,提取对我们有用的数据

python 爬虫第三方库

对于爬虫的初学者,主要掌握三大爬虫库,再在次基础上深入研究,分别为Requests、BeautifulSoup、Lxml

  • Requests

    Requests库作用:请求网站获取返回数据

    import requests
    res = requests.get("https://www.baidu.com")
    print(res.text)

    python爬虫(1)——基本知识和概念_第2张图片
    可以看到程序会返回指定网页的html数据。

    有时候我们也需要在request请求中加入请求头,以达到伪装成浏览器的目的

    import requests
    header = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"
    }
    res = requests.get("https://www.baidu.com",headers = headers)
    print(res.text)

    Request库除了get方法,还有post()方法用于提交表单来爬取需要登录才能获得数据的网站。

    Request库请求也可能会抛出异常,用户可以使用try/catch来进行抓取。常见的异常和错误为:ConnectionError、Timeout、TooManyRedirects

  • BeautifulSoup

    BeautifulSoup是一个常用的模块,可以用其进行解析Request库解析的网页,并将其转为soup文档,从而进一步处理

    from bs4 import BeautifulSoup
    import requests
    res = requests.get("https://www.baidu.com")
    soup = BeautifulSoup(res.text,"html.parser")
    print(soup.prettify())

    输出为:
    python爬虫(1)——基本知识和概念_第3张图片
    这里可以看到通过调用soup的prettify函数,可以将html文件格式化成html文件。在生成soup文档的构造函数中,我使用了html.parser 这个HTML解析器之外,python还提供了其他一些解析器

    解析器 使用方法 优点 缺点
    python标准库 BeautifulSoup(html,”html.parser”) 内置标准、速度始终 容错能力差
    lxml HTML解析器 BeautifulSoup(html,”lxml”) 速度快 需装C库
    lxml XML解析器 BeautifulSoup(html,”xml”) 速度快、唯一支持xml解析的库 需装C库
    html5lib解析器 BeautifulSoup(html,”html5lib”) 容错性强、生成html5文档 速度比较慢

    soup文档对象提供了几个重要的方法来进行元素的定位。

    • find、find_all

      soup.find_all("div","item1") # 查看所有的class=item1的div标签
      soup.find_all("div",class="item1") 
      soup.find_all("div",attrs={"class":"item1"}) 

      对于更加具体的find_all参数,请查看BeautifulSoup的文档
      对于find函数,其实和 find_all 差不多,但是find_all返回的是文档中符合条件的所有tag,是一个tag的集合,但是find方法返回的是一个tag

    • selector

      selector方法用于快速提取信息,在可chrome浏览器控制台中查看selector来获取某个元素的selector

      import requests
      from bs4 import BeautifulSoup
      headers = {
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"
      }
      res = requests.get("http://bj.xiaozhu.com/",headers = headers)
      soup = BeautifulSoup(res.text,"html.parser")
      price = soup.select("#page_list > ul > li:nth-of-type(1) > div.result_btm_con.lodgeunitname > span.result_price > i")
      print(price)  

      返回结果为:[5280]
      其中有一个nth-of-type(1) ,当去掉此处时,返回的就是价格的列表了,调用

      price.get_text()

      即可

  • Lxml

    基于libxml2此XML解析库的python封装,此模块是使用C语言编写,解析速度比BeautifulSoup更快。

你可能感兴趣的:(python)