zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    Overloaded的方法是否可以改变返回值的类型
    parseXXX的用法
    java的类型转换问题。int a = 123456;short b = (short)a;System.out.println(b);为什么结果是-7616?
    UVA 10405 Longest Common Subsequence(简单DP)
    POJ 1001 Exponentiation(大数处理)
    POJ 2318 TOYS(计算几何)(二分)
    POJ 1265 Area (计算几何)(Pick定理)
    POJ 3371 Flesch Reading Ease (模拟题)
    POJ 3687 Labeling Balls(拓扑序列)
    POJ 1094 Sorting It All Out(拓扑序列)
  • 原文地址:https://www.cnblogs.com/TTyb/p/5799564.html
Copyright © 2011-2022 走看看