• python爬虫之BeautifulSoup


    爬虫有时候写正则表达式会有假死现象

    就是正则表达式一直在进行死循环查找

    例如:https://social.msdn.microsoft.com/forums/azure/en-us/3f4390ac-11eb-4d67-b946-a73ffb51e4f3/netcpu100

    所以一般在解析网页的时候可以用BeautifulSoup库来解决网页的正则表达式

    网上对于BeautifulSoup的解释太复杂了

    我就只是选取了我爬虫需要的部分来学习,其他的有需要再去学习,没需要就不浪费时间

    最起码省心了很多

    解释在注释里面都有了

    一句一句的打印出来看就会明白的

     1 #!/usr/bin/python3.4
     2 # -*- coding: utf-8 -*-
     3 import urllib.request
     4 from bs4 import BeautifulSoup
     5 
     6 if __name__ == '__main__':
     7     url = "http://www.lenggirl.com/"
     8     headers = {
     9         'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
    10         'Accept': 'text/html;q=0.9,*/*;q=0.8',
    11         'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
    12         'Accept-Encoding': 'gzip',
    13         'Connection': 'close',
    14         'Referer': None
    15     }
    16     data = urllib.request.urlopen(url).read()
    17     # ('UTF-8')('unicode_escape')('gbk','ignore')
    18     data = data.decode('UTF-8', 'ignore')
    19     # 初始化网页
    20     soup = BeautifulSoup(data, "html.parser")
    21     # 打印整个网页
    22     html = soup.prettify()
    23     # 打印<head>...</head>
    24     head = soup.head
    25     # 打印<body>...</body>
    26     body = soup.body
    27     # 打印第一个<p>...</p>
    28     p = soup.p
    29     # 打印p的内容
    30     p_string = soup.p.string
    31     # soup.p.contents[0]为Aug 22, 2016
    32     # soup.p.contents为[' Aug 22, 2016
                            ']
    33     p_string = soup.p.contents[0]
    34     # 将body里面的所有头打印出来
    35     for child in soup.body.children:
    36         #print(child)
    37         pass
    38     # 将所有的<a>...</a>和<p>...</p>打印出来
    39     a_and_p = soup.find_all(["a","p"])
    40     # 找到<a>...</a>下所有的网址
    41     for myimg in soup.find_all('a'):
    42         img_src = myimg.get('href')
    43         #print(img_src)
    44     # 找到<a>...</a>下类为class_='a'下面的<img>...</img>里面的src
    45     for myimg in soup.find_all('a', class_='a'):
    46         img_src = myimg.find('img').get('src')
    47     # 网页所有信息
    48     #print(html)
  • 相关阅读:
    在CentOS 6.7 64位安装PHP的PDO_OCI扩展 Installing PDO_OCI extension on CentOS 6.7 64bit
    Windows下Apache+PHP+MySQL开发环境的搭建(WAMP)
    在Window上用cmd创建.htaccess文件
    Magento 0元订单 支付方式 -- Magento 0 Subtotal Payment Method
    PHP使用OPENSSL RSA加密解密数据
    CentOS编译安装PHP 7.0
    [转] CentOS单独安装Apache Benchmark压力测试工具的办法
    [转] 基于MySQL的秒杀核心设计(减库存部分)-防超卖与高并发
    快速激活JetBrains PhpStorm WebStorm系列产品
    Mac OS的phpize空信息解决办法
  • 原文地址:https://www.cnblogs.com/TTyb/p/5799564.html
Copyright © 2020-2023  润新知