zoukankan      html  css  js  c++  java
  • 爬虫之Beautfulsoup模块及新闻爬取操作

    今日内容概要

    • IP代理池的概念及使用

    • requests其他方法补充

    • Beautifulsoup模块

      避免你自己写正则表达式

    • 利用该模块爬取京东的商品信息

    今日内容详细

    IP代理池的概念及使用

    1.有很多网站在防爬措施上面都加了封禁IP的措施
        一旦我的网站发现某一个IP在固定的时间内访问了很多次(一分钟访问了30次),那么我会直接获取到该请求对应的主机IP地址,然后加入网站的黑名单
        刚请求来访问我的网站的时候我会先去黑名单中查看当前请求的IP在不在如果在直接拒绝
        如果不在才会进去下一个环节
        
    针对上述IP封禁的情况,出现了IP代理池
        IP代理池里面有很多IP,你每次访问别人的网站的时候
        随机从池子里面有很多IP
        
    具体使用
    
    # 代理的网址获取有免费的也有收费的
    import requests
    proxies={'https':'123.163.117.55:9999',
        'https':'123.163.117.55:9999',
        'https':'123.163.117.55:9999',
    }
    respone=requests.get('https://www.12306.cn',
                         proxies=proxies)
    
    print(respone.status_code)
    

    超时设置

    #超时设置
    #两种超时:float or tuple
    #timeout=0.1 #代表接收数据的超时时间
    #timeout=(0.1,0.2)#0.1代表链接超时  0.2代表接收数据的超时时间
    
    import requests
    respone=requests.get('https://www.baidu.com',
                         timeout=0.0001)
    

    异常处理

    # 万能异常
    try:
        # kasd
        l = [111,222]
        l[3]
    except Exception as e:
        print(e)
    

    发送文件

    import requests
    files={'file':open('a.txt','rb')}
    respone=requests.post('http://httpbin.org/post',
                          files=files)
    print(respone.status_code)
    

    解析json

    #解析json
    import requests
    response=requests.get('http://httpbin.org/get')
    
    import json
    res1=json.loads(response.text) #太麻烦
    
    res2=response.json() #直接获取json数据
    
    print(res1 == res2) #True
    

    Beautiful Soup模块

    Beautiful Soup会帮你节省数小时甚至数天的工作时间
    
    # 安装 Beautiful Soup
    pip install beautifulsoup4  # 这个4千万不要少了
    
    
    # 解析器
    	有四种 常用的两种
        html.parse  内置的不需要下载
        lxml		需要下载
        	pip3 install lxml
     
    # 导入
    from bs4 import BeautifulSoup
    

    基本使用

    from bs4 import BeautifulSoup
    html_doc = """
    <html><head><title>The Dormouse's story</title></head>
    <body>
    <p class="title"><b>The Dormouse's story</b></p>
    
    <p class="story">Once upon a time there were three little sisters; and their names were
    <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
    <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
    <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
    and they lived at the bottom of a well.</p>
    
    <p class="story">...</p>
    """
    from bs4 import BeautifulSoup
    
    # 先将html页面内容传入BeautifulSoup 生成一个对象
    soup = BeautifulSoup(html_doc, 'lxml')  # 具有容错功能
    
    res = soup.prettify()  # 处理好缩进,结构化显示  美化
    print(res)
    

    爬取汽车之家新闻

    1.爬取汽车之家的新闻数据
    2.先查看汽车之家新闻加载规律
    	默认会先展示一个ul
        	下面隐藏了三个ul
        最后有一个分页器
    3.研究分页页码变化
    	https://www.autohome.com.cn/news/1/#liststart
        https://www.autohome.com.cn/news/2/#liststart
        https://www.autohome.com.cn/news/3/#liststart
        https://www.autohome.com.cn/news/4/#liststart
    4.访问新闻数据页 研究是否有一些简单的防爬措施
    5.研究新闻数据都在哪个标签内
    6.从标签内提取想要的新闻数据,并移除干扰项
    	
    # 代码
    res = requests.get(url)  # 前期访问没有任何的小防爬措施
        # print(res.text)
    
        # 将爬取到的页面传入bs4类中生成对象
        soup = BeautifulSoup(res.text,'lxml')
    # 查找新闻所在的标签 然后获取标签内想要的数据
        # 1.查找div标签
        div = soup.find(id='auto-channel-lazyload-article')  # 利用id查找标签
        # print(div)
    
        # 2.找ul标签
        ul = div.find(name='ul')  # 利用标签名查找标签  只拿第一个
        # ul_list=div.find_all(class_="article")   #找出下面所有类名为article的标签   class关键字所以需要加下划线区分
        # print(len(ul_list))
        # print('+++++++++++++++++++++++++++')
        # print(ul)
    
        # 3.找li标签
        # li = ul.find(name='li')  # 只会拿到第一个
        li_list = ul.find_all(name='li')  # 拿内部所有的li 并且组织成列表的形式
     # 4.从li中提取我们想要的数据
        """
        <li data-artidanchor="1038223">
        <a href="//www.autohome.com.cn/news/202009/1038223.html#pvareaid=102624">
        <div class="article-pic"><img src="//www2.autoimg.cn/newsdfs/g3/M01/B5/C1/120x90_0_autohomecar__ChsEkV9i0DiAKHchAAGGvdkeT_A835.jpg"/></div>
        <h3>主打年轻化市场 宝马128ti低伪谍照曝光</h3>
        <div class="article-bar">
        <span class="fn-left">30分钟前</span>
        <span class="fn-right">
        <em><i class="icon12 icon12-eye"></i>827</em>
        <em data-articleid="1038223" data-class="icon12 icon12-infor"><i class="icon12 icon12-infor"></i>0</em>
        </span>
        </div>
        <p>[汽车之家 海外谍照]  日前,宝马集团官方放出了一组宝马128ti的轻度伪装图,这款车已在纽博格林赛道完成了最后的测试,并将于11月在海外市场投放。...</p>
        </a>
        </li>
        """
        # for循环依次获取数据
        for li in li_list:
            # 1.先获取新闻的标题
            h3 = li.find(name='h3')
            # print(h3)
            # 优化 移除干扰项
            if h3:
                # 获取h3里面的文本
                news_title = h3.text
                # print(news_title)
    
            # 2.获取新闻链接
            a = li.find(name='a')
            # 移除干扰项
            if a:
                news_link = a.get('href')
                # print(news_link)
     # 3.获取图片链接
            img = li.find(name='img')
            if img:
                news_img = img.get('src')
                # print(news_img)
    
            # 4.获取新闻简介
            p = li.find(name='p')
            if p:
                news_info = p.text
                # print(news_info)
    
            res = """
            新闻标题:%s
            新闻链接:%s
            新闻图片:%s
            新闻简介:%s
            """%(h3,news_link,news_img,news_info)
            print(res)
    

    更多操作方法

    html_doc = """
    <html><head><title>The Dormouse's story</title></head>
    <body>
    <p id="my p" class="title jason" username="jason">123<b id="bbb" class="boldest">The Dormouse's story</b></p>
    
    <p class="story">Once upon a time there were three little sisters; and their names were
    <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
    <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
    <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
    and they lived at the bottom of a well.</p>
    <p class="story">...</p>
    """
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html_doc,'lxml')
    
    # print(soup.a)  # 查找a标签 只会拿第一个
    
    # print(soup.p.name)  # 获取标签名
    
    # print(soup.p.attrs)  # 用字典的形式给你列举出标签所有的属性
    # {'id': 'my p', 'class': ['title'], 'username': 'jason'}
    
    print(soup.p.text)  # 获取p标签内部所有的文本
    # string用的很少
    # print(soup.p.string)  # 只有p下面有单独的文本的时候才能拿到
    

    总结

    1.查找标签非常的简单
    	find()
        find_all()
    """
    括号内常用的参数
    	name		根据标签的名字查找标签
    	id			根据标签的id查找标签
    	class_      根据标签的class查找
    """
    
    2.查找标签内部的文本
    	标签对象.text
        
    3.查找标签属性对应的值
    	a标签的href属性对应的值
        	a.get('href')
        img标签的src属性对应的值
    		img.get('src')
    
    为了舒适的结果,眼前的坎坷路程即使再长都是值得的。
  • 相关阅读:
    MySQL 子查询
    mysql3
    mysql2
    mysql
    C语言理论知识
    冒泡排序
    猜数字游戏
    WPF清爽酷炫的界面Mahapps.metro
    如何在.net4.0中使用.net4.5的async/await
    在C#中使用官方驱动操作MongoDB
  • 原文地址:https://www.cnblogs.com/abudrSatan1998/p/13688443.html
Copyright © 2011-2022 走看看