zoukankan      html  css  js  c++  java
  • 爬虫之汽车之家/抽屉新热榜/煎蛋网

    alex http://www.cnblogs.com/alex3714/articles/5465198.html

    one

    http://www.runoob.com/python3/python3-tutorial.html
    
    python是一门编程语言,作为学习python的开始,需要事先搞明白:编程的目的是什么?什么是编程语言?什么是编程?
    编程的目的:
    #计算机的发明,是为了用机器取代/解放人力,而编程的目的则是将人类的思想流程按照某种能够被计算机识别的表达方式传递给计算机,从而达到让计算机能够像人脑/电脑一样自动执行的效果。    
    
    什么是编程语言?
    #上面提及的能够被计算机所识别的表达方式即编程语言,语言是沟通的介质,而编程语言是程序员与计算机沟通的介质。在编程的世界里,计算机更像是人的奴隶,人类编程的目的就命令奴隶去工作。
    
    python的创始人为吉多·范罗苏姆(Guido van Rossum)。1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序
    python是一门富含优雅设计理念的编程语言  import this
    
    Python可以应用于众多领域,如:数据分析、组件集成、网络服务、图像处理、数值计算和科学计算等众多领域。
    目前业内几乎所有大中型互联网企业都在使用Python,
    如:Youtube、Dropbox、BT、Quora(中国知乎)、豆瓣、知乎、Google、Yahoo!、Facebook、NASA、百度、腾讯、汽车之家、美团等。
    互联网公司广泛使用Python来做的事一般有:自动化运维、自动化测试、大数据分析、爬虫、Web 等。
    
    python是一门解释性语言,由解释器逐行读取python代码,并执行
    go是编译型语言,编译器把源程序的每一条语句都编译成机器语言,并保存成二进制文件,这样运行时计算机可以直接以机器语言来运行此程序,速度很快
    
    安装python3.6解释器
    安装pycharm软件
    测试python解释器,交互式,第一个hello world
    变量
        变量名只能是 字母、数字或下划线的任意组合
        变量名的第一个字符不能是数字
        关键字不能声明为变量名
        每个变量有三个属性    print(type(a),id(a),a)
    列表
    字典
    常量
    input
    注释
    bool
        a > b  True/False 
        # 1、None,0,空(空字符串,空列表,空字典等)三种情况下布尔值为False
        # 2、其余均为真
    格式化输出
        %s
        %d
    运算符
        +
        -
        *
        /
        +=
    if else 
        #小红age=19
        age=33
    
        if age > 40:
            print('阿姨再见')
        elif age <30:
            print('小姐姐有空吗')
        else:
            print('大龄...')
    
    while True:
        print('aa')
        print('bb')
        print('cc')
    print('dd') #这辈子走不到dd这一行
    
    
    count = 0
    while count <20:
        count+=1
        print(count)
        if count ==8:
            break
    
    for i in [1,2,3,4,5]:
        print(i)
    
    for i in {'name':'chaoge','age':18}:
        print(i)
    
    for i in range(10):
        if i == 8:
            continue
        print('i的值是:', i)
    
    可变
        列表,字典
        l1=[1,2,3]
        id(l1)
        l1[0]=4
        id(l1)
    不可变
        数字
        字符串
        元祖
        s1='oldboy'
        id(s1)
        s1='oldgirl'
        id(s1) 
    字符串
        s1='oldboy'
        索引 012345
        s1[index]
        s1[1]  正向取索引1的值
        s1[-1] 反向取索引-1的值,从后往前取
    切片
        顾头不顾尾,步长,默认步长1
        s1='oldboy'
        s1[0:3:2]   'od'
        s1[0:4]  'oldb'
        s1[::]    'oldboy'
        s1[::-1]  'yobdlo'
    len
        len(s1)
        s1.__len__()
    成员运算in,not in 
        s1='oldboy'
        'c' in s1 
        'c' not in s1
    移除前后的空白
        s1='    my name is yuchao    '
        s1.strip()
        name=input().strip()
    分割split
        chaoge='chaoge|18|180|1800'
        chaoge.split('|') #返回一个列表
    大写小写转化
        chaoge='ABCDEFG'
        chaoge.lower()
        chaoge.upper()
        addr=input().upper()
    format格式化输出
         info='my name is {},my age is {}'.format('yuchao',18)
         info='my name is {name},my age is {age}'.format(age=18,name='chao')
         info='my name is {0},my age is {1},i am real age {1},really{1}'.format('chao',18)
    字符串拼接
        s1='old'
        s2='boy'
        s1+s2
    替换
        info='my name is chaoge,my name is chaoge'
        info.replace('chaoge','yuchao')
        info.replace('chaoge','yuchao',1) #替换一次
    判断全数字
        age='123123e'
        age='123123'
        age.isdigit()
    
        age=input('input your age:')
        if age.isdigit():
            age=int(age)
            print('你的年纪是%s'%age)
        else:
            print('输入的age非法,重新输入')
    count统计次数
        info='my name is yuchao,my name is yuchao and yuchao'
        info.count('yuchao')
    one

    two

    print()默认有一个换行符
    print('aaa',end='')
    print('bbb')
    
    列表操作
        l1=[1,'chao',[6,6],{'name':'chao'}]
        #按照索引取值
        l1[0]
        l1[-1]
        #正负索引修改值
        l1[0]=2
        l1[-1]=3
        #修改[6,6]的值
        l1[2][1]=7
    切片
        顾头不顾尾 步长
        l2=l1[0:3:2]
    长度
        l1.__len__()
        len(l1)
    成员运算 in not in 
        1 in l1
        2 not in l1
    在末尾追加
        l1.append(3)
        l1.append('chao')    
        l1.append([1,2])
    删除
        a=10
        del a
        del l1[1]
        l1.remove(1)
        l1.remove('chao')
        l1.pop()#删除结尾一个元素
    for遍历列表
        for i in l1:
            print(i)
        for i in range(len(l1)):
            print(l1[i])
    列表的index/count方法
        l1.index(1)
        l1.count('chao')
    extend扩展
        l1.extend([1,2,3])
        l1.extend(l2)
    clear清空列表
        l1.clear()
    反转,倒叙
        l1.reverse()
    
    
    元祖
        定义
        age = (11, [1, 3, 4], 33, 44, 55)
        age=tuple([11,22,33,44])#传入可迭代对象
    索引取值
    切片
    长度
    成员运算
    for循环
    
    字典
        定义:key必须是不可变类型,value可以是任意类型
        dic={'name':'chao','age':18}
        dic=dict({'name':'chao','age':18})
        dic=dict(name='egon',age=18)
    按key取值,可取可存
        dic['addr']='huaian'
    长度len
    成员运算in not in 
    删除
        dic.pop('addr')
    clear清空
    valus取出所有值
        dic.values()
    keys取出所有键
        dic.kyes()
    
    集合类型
        set1={'alex','egon','wupeiqi'}
        type(set1)
    集合添加数据
        set1.add('yuanhao')
    清空clear
        
    文件处理 ,r是读,t是文本模式
    f=open(r'C:UsersadminPycharmProjects	est	est','r',encoding='utf-8')
    print(f)
    data=f.read()
    print(data)
    f.close()
    
    
    with open('/tmp/test.txt' ,'r')as f:
        print(f.read())
    
    上面都是读,r,接下来使用w,写模式
    w模式打开文件,他会清空文件,需要注意,文件不存在默认会创建
    with open('/Users/yuchao/PycharmProjects/oldboy_python/ghostdriver.log' ,'w')as f:
        f.write('test file
    ')
        f.write('test hello
    ')
    由于w每次打开都会清空文件,因此内容永远是这2行
    
    #追加写入可以用a模式
    with open('/Users/yuchao/PycharmProjects/oldboy_python/ghostdriver.log' ,'r')as f:
        f.write('test file
    ')
        f.write('test hello
    ')
    
    #读取图片数据并且写入到一个新图片
    with open('/Users/yuchao/PycharmProjects/oldboy_python/girl.jpg' ,'rb')as f:
        with open('new_girl.JPG','wb')as f1:
            f1.write(f.read())
    
    函数
        def关键词定义函数,定义阶段只检测语法,不执行代码
        调用阶段,执行代码
        先执行再调用
    无参函数定义,调用
        def foo():
            print('hello foo')
        foo()#调用
    空函数,pass
        def foo():
            pass
    
    有参函数定义,调用
        def foo2(arg):
            print('foo2传入的参数arg是',arg)
        foo2('chaoge')
    函数返回值
        def foo3(a,b):
            return a+b
        foo3(3+2)
    函数无return,默认返回None
        def foo3():
            pass
        print(foo3()) #None
    以上都是位置参数
    关键词参数
        foo(a=3,b=4)
    可变长参数,*args,位置传参,*args接收一个元祖
    def foo(a,b,*args):
        print(a)
        print(b)
        print(args)
    foo(1,2,3,4,5)
    可变长参数,关键词传参,**kwargs接收一个字典
    def foo(x,y,**kwargs):
        print(x)
        print(y)
        print(kwargs)
    foo(1,2,z=12,u=10)
    函数名字可以当做变量传递
    def foo(x,y,**kwargs):
        print(x)
        print(y)
        print(kwargs)
    a=foo
    print(a)
    a(1,2,z=12,u=10)
    函数名可以当做参数传递
    def foo():
        print('hello')
    
    def foo2(func):
        func()
    foo2(foo)
    函数嵌套
    def foo():
        def inner():
            print('i am inner')
        return inner
    
    f=foo()
    f()
    闭包函数
    内部函数包含对外部作用域而非全局作用域的引用
    x=100
    def foo():
        x=10
        def inner():
            print(x)
        return inner
    f=foo()
    f()
    
    模块
    模块就是别人写好的python代码文件/文件夹,使用from 文件夹 import 模块
    
    import time
    print(time.strftime('%Y-%m-%d %T'))
    
    import random
    print(random.randint(10,20))
    
    import os
    os.remove('new_girl.JPG')
    
    import os
    print(os.mkdir('test'))
    
    pip3 install Flask
    from flask import Flask
    app=Flask(__name__)
    app.debug=True
    @app.route('/index')
    def index():
        return 'hello huaian'
    if __name__ == '__main__':
        app.run()
    two

    three

    什么是爬虫技术?
    互联网你就可以想象成一个巨大蜘蛛网,爬虫程序就是网上的爬虫机器人,它从出生就放在了网络上,一直开始爬行,遇见什么就捉住什么
    互联网公司哪家爬虫开发做的最牛?百度,谷歌,搜索引擎就是一个巨大的爬虫
    今日头条app的新闻,点一下,唰就调到了另一个页面,然后蹦出一些新闻,这就是今日头条爬取的其他公司的新闻信息
    我有一个大学同学,她是学设计的,毕业后他就去了上海,社交app的,她负责摄影,去全国各地拍照,写文章,然后推到公司的文章页面,
    但是这样太费钱了啊,而且效率很低,出文章产品率非常低
    那他们公司就想了个办法,招了个nb的爬虫程序员,让他写程序,在整个互联网,各家做旅游最nb的公司,去爬取他们公司发布的图片,然后自己再进行处理
    因此这个爬虫程序是需要遵循法律责任的,不得爬取别人有原创版权的作品,进行自己的商业使用。每个互联网公司都是遵循的robots.txt协议的那些能爬,哪些不能爬
    
    我们平时访问资源,都是浏览器访问一个url,发起一个请求,别人返还给你数据
    因此爬虫就是通过代码模拟浏览器发起请求,获取别人的内容
    使用的模块就是requests
    bs4模块用于解析响应的内容
    
    互联网通信,web协议介绍
    https://www.cnblogs.com/pyyu/p/9467256.html 
    
    
    下载图片
    import requests
    data=requests.get('http://www.pythonav.cn/av/man.jpg')
    with open('1.jpg','wb') as f:
        f.write(data.content)
    
    
    介绍了http web基础,开始requests模块讲解
    http://www.cnblogs.com/wupeiqi/articles/6283017.html
    
    爬取汽车之家的新闻
    爬取抽屉的新闻
    点赞抽屉网的文章
    three

    汽车之家新闻:

    import requests
    from bs4 import BeautifulSoup
    import os
    
    # 模拟浏览器发请求
    r1 = requests.get(url='https://www.autohome.com.cn/news/')
    # print(r1) #<class 'requests.models.Response'>
    r1.encoding = 'gbk'  # 解决乱码问题
    # print(r1.text)#打印网页文本
    # print(r1.content)#打印网页bytes数据
    
    # bs4解析响应体对象
    soup = BeautifulSoup(r1.text, 'html.parser')
    # print(soup)
    
    # bs4查找标签
    container = soup.find(name='div', attrs={'id': 'auto-channel-lazyload-article'})
    li_list = container.find_all(name='li')
    # print(type(li_list))#<class 'bs4.element.ResultSet'>
    for tag in li_list:
        # 过滤出所有title <h3>标签
        title = tag.find(name='h3')
        if not title:
            continue
        # 简介
        summary = tag.find(name='p')
        # 文章url
        # a是找到的tag,字典数据
        a = tag.find(name='a')
        url = "https:" + a.attrs.get("href")
        # 图片url
        img = tag.find(name='img')
        img_url = "https:" + img.get("src")
        print('标题:', title.text)
        print('简介:', summary.text)
        print('url:', url)
        print('图片地址:', img_url)
        print('-' * 100)
    
    # 保存图片
    r2 = requests.get(url=img_url)
    file_name = img_url.rsplit('/', maxsplit=1)[1]
    file_path = os.path.join('imgs', file_name)
    with open(file_path, 'wb')as f:
        f.write(r2.content)
    autohome.py
    import requests
    from bs4 import BeautifulSoup
    import os
    
    r1 = requests.get(
        url="https://www.autohome.com.cn/news/",
    
    )
    r1.encoding = 'gbk'
    
    # 文章内容开始
    '''
    auto-channel-lazyload-article
    '''
    # 使用python的bs4模块处理汽车之家的响应内容
    # 创建一个soup对象
    soup = BeautifulSoup(r1.text, 'html.parser')
    # 通过bs4提供的标签查找法进行标签过滤
    # 找到文章内容所有
    # container = soup.find(name='div', attrs={'id': 'auto-channel-lazyload-article'})
    article_all = soup.find(name='div', attrs={'class': 'article-wrapper'})
    # 然后继续过滤,发现每一篇文章都存在li标签下
    # find_all找到所有的li标签,返回的是一个列表数据,因此就可以for遍历,分离出每一个li
    li_list = article_all.find_all(name='li')
    for tag in li_list:
        # 遍历出每一个tag之后,就可以找到tag中的标题title
        title = tag.find(name="h3")
        # 发现这里有None空数据因此做个判断
        if not title:
            # 如果title为空,就跳过当前循环
            continue
        # print(title.text)
        # 文章内容
        content = tag.find(name='p')
        # print(content.text)
        # 文章地址,先找到a标签,然后取出a标签的href属性,通过a.attrs得到a标签属性,字典数据
        a = tag.find(name='a')
        # print(a.attrs)#字典数据就可以通过get取值,还得拼接url全路径
        url = "https:" + a.attrs.get("href")
        # print(url)
        # 图片地址
        img = tag.find(name="img")
        img_url = "https:" + img.attrs.get("src")
        # print(img_url)
    
    
        #因此我们可以格式化输出新闻信息
        print("文章标题:    ",title)
        print('文章详情:    ',content)
        print('文章地址:    ',url)
        print("文章图片地址:  ",img_url)
        print('-'*50)
        #下载所有图片
        data=requests.get(url=img_url)
        #图片名字分割url,分割一次,得到2个值,取索引1的值
        img_name=img_url.rsplit('/',maxsplit=1)[1]
        img_path=os.path.join('img',img_name)
        with open(img_path,'wb') as f:
            f.write(data.content)
            
    print("下载完成,图片保存在Img文件夹")
    详细注释版

    抽屉新热榜新闻

    import requests
    import os
    from bs4 import BeautifulSoup
    
    # 抽屉不加请求头的话,默认403终止了
    r1 = requests.get(
        url='https://dig.chouti.com/',
        headers={
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
        }
    )
    
    soup = BeautifulSoup(r1.text, 'html.parser')
    # 内容区域
    container = soup.find(name='div', attrs={'class': "content-list"})
    div_list = container.find_all(name='div')
    for tag in div_list:
        title = tag.find(name="a", attrs={'class': "show-content color-chag"})
        if not title:
            continue
        summary = tag.find(name="div", attrs={"class": "area-summary"})
        if not summary:
            continue
        a = tag.find(name="a")
        url = "https:" + a.attrs.get("href")
        img = tag.find("img")
        # 获取img的源地址,可能有None,因此要做判断
        img_url = img.get("original")
        if not img_url:
            continue
        img_url = "https:" + img_url
        # 下载缩略图
        r2 = requests.get(
            url=img_url
        )
        file_namne = img_url.rsplit("/", maxsplit=1)[1]
        file_namne = file_namne.rstrip("?quality=80")
        file_path = os.path.join("img2", file_namne)
        with open(file_path, 'wb') as f:
            f.write(r2.content)
        print("标题:",title.text.strip())
        print("简介:",summary.text)
        print("文件链接:",url)
        print("图片链接",img_url)
    抽屉新闻,图片
    import requests
    
    r1 = requests.get(
        url="https://dig.chouti.com/",
        headers={
            'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
        },
    )
    # 浏览器发起请求,获取cookie
    r1_cookie_dict = r1.cookies.get_dict()
    print(r1_cookie_dict)
    
    # 提交登录,https://dig.chouti.com/login
    r2 = requests.post(
        url="https://dig.chouti.com/login",
        # 携带请求头
        headers={
            'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
        },
        # 此处是抽屉网提交登录的Form data
        data={
            'phone': "8615210858004",
            "password": "a6081798",
            "oneMonth": 1
        },
        # 提交cookie
        cookies=r1_cookie_dict
    )
    ###点赞
    # 点击点赞时,获取的点赞url,地址是:https://dig.chouti.com/link/vote?linksId=21775786,点赞提交方式是POST
    # 取消点赞的url是:https://dig.chouti.com/vote/cancel/vote.do
    
    
    rsp = requests.get(
        url="https://dig.chouti.com/",
        headers={
            'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
        },
    )
    
    from bs4 import BeautifulSoup
    
    # bs4解析,查找标签
    soup = BeautifulSoup(rsp.text, "html.parser")
    div = soup.find(attrs={'id': 'content-list'})
    
    items = div.find_all(attrs={"class": "item"})
    for item in items:
        tag = item.find(attrs={"class": "part2"})
        nid = tag.get("share-linkid")
        #循环根据nid进行点赞
        r1 = requests.post(
            # 循环遍历点赞,取出linksid
            url="https://dig.chouti.com/link/vote?linksId=%s" % nid,
    
            # 取消点赞发送的地址,必须带上链接ID
            # url="https://dig.chouti.com/vote/cancel/vote.do",
            # data={
            #     "linksId": 21775786
            # },
    
            headers={
                'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
            },
            # 同一个cookie,身份验证
            cookies=r1_cookie_dict
        )
        print(r1.text)
    抽屉点赞
    import requests
    from bs4 import BeautifulSoup
    import os
    
    r1 = requests.get(url="http://dig.chouti.com",
                      headers={
                          # 模拟浏览器客户端
                          "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"})
    # print(r1.text)
    
    # bs4解析
    soup = BeautifulSoup(r1.text, 'html.parser')
    # print(soup)
    # 找到内容显示区域
    content = soup.find(name="div", attrs={"class": "content-list"})
    # print(content)
    # 每一个div,item是每一个文章块,返回一个列表
    item = content.find_all(name="div", attrs={"item"})
    for tag in item:
        # 遍历每一个item内容块,标题就是a标签的text值
        title = tag.find(name='a')
        # print(title.text)
        # 摘要信息
        summary = tag.find(name="span", attrs={"class": "summary"})
        if not summary:
            continue
        # print(summary.text)
        # 文章链接,通过attrs方法获取字典数据
        url = tag.find(name="a").attrs.get("href")
        # print(url)
        # 缩略图
        img_url = tag.find(name="img", attrs={"alt": "抽屉新热榜"})
        img_url = "https:" + img_url.get("original")
        print("文章标题:    ", title.text.strip())
        print("文章摘要:    ", summary.text)
        print("文章链接:    ", url)
        print("图片链接:    ", img_url)
        print("-————"*20)
        #下载图片
        img1=requests.get(url=img_url)
        img_name=img_url.rsplit("/",maxsplit=1)[1]
        img_name=img_name.rsplit("?quality=80")[0]
        print(img_name)
        img_path=os.path.join("img2",img_name)
        with open(img_path,'wb') as f:
            f.write(img1.content)
    注释版抽屉

    登录github

    import requests
    
    # 访问github页面
    r1 = requests.get(
        url="https://github.com/login"
    )
    r1_cookie_dict = r1.cookies.get_dict()
    # print(r1.text)
    # bs4解析页面
    from bs4 import BeautifulSoup
    
    s1 = BeautifulSoup(r1.text, "html.parser")
    
    token = s1.find(name="input", attrs={"name": "authenticity_token"}).get("value")
    print(token)
    r2 = requests.post(
        url="https://github.com/session",
        data={
            "commit": "Sign in",
            "utf8": "",
            "authenticity_token": token,
            "login": "",
            "password": ""
        },
        cookies=r1_cookie_dict
    )
    print(r2.text)
    github登录
  • 相关阅读:
    ubuntu12.04启动系统时报错
    TCP&HTTP协议详解
    nginx日志分析、切割与防盗链
    Nginx Rewrite规则详解
    nginx location深入剖析
    hadoop自动安装脚本
    极易中文分词
    朴素贝叶斯算法分析及java 实现
    随机森林(Random Forest)
    ubuntu 13.04 安装 JDK
  • 原文地址:https://www.cnblogs.com/pyyu/p/9560924.html
Copyright © 2011-2022 走看看