zoukankan      html  css  js  c++  java
  • 03_多协程爬取糗事百科热图

    今天在使用正则表达式时未能解决实际问题,于是使用bs4库完成匹配,通过反复测试,最终解决了实际的问题,加深了对bs4.BeautifulSoup模块的理解。

    爬取流程

    前奏:

    分析糗事百科热图板块的网址,因为要进行翻页爬取内容,所以分析不同页码的网址信息是必要的

    具体步骤:

    1,获取网页内容(urllib.request)# 糗事百科有发爬虫技术,所以要添加headers,伪装程浏览器

    2,解析网页内容,获取图片链接(from bs4 import BeautifulSoup)

    3,通过图片链接下载图片(urllib.request),并存储到本地

    备注:

    具体的爬取说明在代码都有详细的解释

      1 import urllib.request
      2 import requests
      3 from bs4 import BeautifulSoup
      4 # import re
      5 import gevent
      6 from gevent import monkey
      7 import bs4
      8 
      9 monkey.patch_all()
     10 
     11 
     12 def get_html_text(url, raw_html_text, depth):
     13 
     14     # 爬取网页数据
     15 
     16     # 糗事百科有反爬虫机制,需要设置请求头伪装成浏览器
     17     hd = ('User-Agent','Mozilla/5.0(Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Ch    rome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0')
     18 
     19     # 创建opener对象
     20     opener = urllib.request.build_opener()
     21     opener.addheaders = [hd]
     22 
     23     # 将opener对象设置为全局
     24     urllib.request.install_opener(opener)
     25 
     26     # 翻页爬取html_text
     27     for i in range(depth):
     28         # 根据对网址的分析,构造符合翻页时的网址
     29         url_real = url + str(i+1)
     30         try:
     31             html_data = urllib.request.urlopen(url_real).read().decode('utf-8', 'ignore')
     32             raw_html_text.append(html_data)
     33             # 测试代码
     34             # print(len(html_data))
     35         except Exception as result:
     36             print('错误类型:', result)
     37     
     38     print('提取网页信息完成...')
     39     return raw_html_text
     40     # 测试代码         
     41     # print(len(raw_html_text))
     42 
     43 
     44 def parser_html_text(raw_html_text, done_img):
     45 
     46     # 对爬取的网页数据进行遍历
     47 
     48     for html_text in raw_html_text:
     49         # 使用BeautifulSoup对网页进行解析
     50         soup = BeautifulSoup(html_text, 'html.parser')
     51         # 使用soup.find_all('div','thumb') 查找出每个网页中所有标签是div,属性值是thumb的标签
     52         # 通过对网页源代码的分析,图片信息都存储在该标签下的孙子标签img中的属性src中
     53         # 遍历每个div标签
     54         for tag in soup.find_all('div', 'thumb'):
     55             # 判断 tag 是否是bs4.element.Tag属性,因为在标签div下,并不是全部是标签
     56             if isinstance(tag, bs4.element.Tag):
     57                 # 遍历每个div标签下的所有孙子标签
     58                 for img in tag.descendants:
     59                     # 判断标签的名字是不是‘img’,如果是,取出标签中属性src的属性值。
     60                     if img.name == 'img':
     61                         link = img.get('src')
     62                         done_img.append(link)
     63     #测试代码
     64     #print(done_img)
     65     print('网页解析完成...')
     66     return done_img
     67 
     68 def save_crawler_data(done_img):
     69     # 将目标文本存储到本地‘./’表示当前目录
     70     path = './img/'
     71     # enumerate(list) 返回索引及索引对应的列表内的元素
     72     for i,j in enumerate(done_img):
     73         # 分析爬取的链接,前面缺少‘https:’,使用字符串拼接
     74         j ='https:' + j
     75         # 通过urllib.request.urlopen()下载图片
     76         try:
     77             img_data = urllib.request.urlopen(j).read()
     78             path_real = path + str(i+1)
     79             with open(path_real, 'wb') as f:
     80                 f.write(img_data)
     81         except:
     82             continue
     83     print('图片存储完成')
     84 
     85 
     86 def main():
     87     url = 'https://www.qiushibaike.com/imgrank/page/'
     88     depth = 20
     89     raw_html_text = list()
     90     done_img = list()
     91     Raw_html_text = get_html_text(url, raw_html_text, depth)
     92     Done_img = parser_html_text(Raw_html_text, done_img)
     93     gevent.joinall([
     94         gevent.spawn(get_html_text,url,raw_html_text,depth),
     95         gevent.spawn(parser_html_text,Raw_html_text,done_img),
     96         gevent.spawn(save_crawler_data,Done_img)
     97         ])
     98 
     99     save_crawler_data(done_img)
    100 
    101 
    102 if __name__ == '__main__':
    103     main()
  • 相关阅读:
    Balanced Binary Tree
    Convert Sorted List to Binary Search Tree
    Convert Sorted Array to Binary Search Tree
    Binary Tree Zigzag Level Order Traversal
    Validate Binary Search Tree
    Binary Tree Level Order Traversal II
    Binary Tree Level Order Traversal
    Maximum Depth of Binary Tree
    如何把U盘的两个盘或者多个盘合成一个
    bugku 想蹭网先解开密码
  • 原文地址:https://www.cnblogs.com/summer1019/p/10398688.html
Copyright © 2011-2022 走看看