python爬虫学习(一)

【1】安装python以及requests、bs4第三方库

【2】面向过程编程、面向对象编程、函数式编程

    面向过程编程:根据业务逻辑从上到下写代码

    面向对象编程: 各函数之间有一定的关联性(特点:封装和继承)

    函数式编程:函数之间独立无公用数据

【3】编写第一个简单爬虫

  a、获取页面

    import requests
    from bs4 import BeautifulSoup
    link="http://www.santostang.com/"
    headers={"User-Agent":"Mozilla/5.0(Windows;U;Windows NT6.1;en-US;rv:1.9.1.6)Gecko/20091201 Firefox/3.5.6"}  #定义请求头的浏览器代理,伪装成浏览器
    r=requests.get(link,headers=headers)

  b、提取并存储数据

    soup=BeautifulSoup(r.text,"html.parser")       #BeautifulSoup对页面进行解析
    title=soup.find("h1",class_="post-title").a.text.strip()
    with open("first.txt","a+") as file:  #创建并打开一个名为“first.txt”的文件    a+为附加模式打开文件,在原有的内容后添加内容
         file.write(title)

【4】其他

  */*  numbers(数字)、strings(字符串)、tuples(元组)为不可变数据类型,list(列表)、dict(字典)为可变数据类型

   ------Exam1------    

      a=1

      def fun(a):

       a=2

      fun(a)

      print(a)    #输出结果为???             1

                  ----------------------------------------------------------------------

      b=[ ]

      def func(b):

        b.append[1]

      func(a)

      print(a)    #输出结果为???             [1]

   ------Exam2------  

     class Person():

       name="zhangsan" 

      p1=Person()

      p2=Person()

      p1.name="lisi"

      print(p1.name)  #输出结果为???            lisi

      print(p2.name)  #输出结果为???            zhangsan

      print(Person.name)  #输出结果为???          zhangsan

                 --------------------------------------------------------------------------------- 

     class Person2():

       list=[ ] 

      p1=Person2()

      p2=Person2()

      p1.list.append(1)

      print(p1.list)  #输出结果为???              [1]

      print(p2.list)  #输出结果为???              [1]

      print(Person2.list)  #输出结果为???             [1]

原文地址:https://www.cnblogs.com/momingzhong/p/11901227.html