简单爬虫总结

简单爬虫总结

网页加载

加载方法

  • urlopen
    • from urllib.request import urlopen
    • html = urlopen('网址').read().decode('utf-8')
    • #返回的是网页的源码,字符串
  • requests
    • import requests
    • html = requests.get('网址')#返回的是requests的对象
    • html.text #可以得到文字

浏览器伪装

import requests  
headers = {  
    'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)\Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763"  
}  
html = requests.get('网址', headers=headers).text  

网页解析

正则表达式

  • import re
  • re.findall(r'条件', html)
  • #返回搜索结果构成的列表
  • 详见

BeautifulSoup模块

  • from bs4 import BeautifulSoup

  • soup = BeautifulSoup(html, features='lxml') #构建对象,选取解析方式

  • 点域访问

    • soup + ‘.’ + 标签(head, h1, p….)
  • find_all 只能对一个元素进行查找

    • find_all(‘标签’) #返回所有标签构成的列表
    • 对于每个标签内部可以使用类似字典的方式访问每个关键字描述
       all_href = soup.find_all('a')  
       for i in all_href:  
         print(i['href'])  
  • 高级find_all

    • month = soup.find_all('标签', {'关键子':'描述',....})

      • 只要关键字描述中识别到了描述条件便符合匹配,返回构成的列表,:

          month = soup.find_all('li', {'class':'month'})  
          print(month)  
        
          [<li class="month">一月</li>, <li class="feb month">二月</li>, <li class="month">三月</li>, <li class="month">四月</li>, <li class="month">五月</li>]  
    • 描述使用正则表达式

      • 对条件格式化 re.compile('正则条件')

文件下载

前期准备

import os  
os.markdirs('路径文件夹', exist_ok=True) # 建立路径,如果已经存在则直接访问  

下载

  • urlretrieve

      from rullib.request import rulretrieve  
      url  
      urlretrieve(IMAGE_RUL, '路径与文件名')  
  • requests

      import requests  
      r = requests.get(IMAGE_RUL)  
      with open('路径与文件名', 'wb') as f:  
          f.write(r.content)      # whole document  
  • 大文将处理(边下边存)

      r = requests.get(IMAGE_RUL, stream=True) # stream loading  
    
      with open("路径与文件名", 'wb') as f:  
          for chunk in r.iter_content(chunk_size=32):  
              f.write(chunk)  

    练习下载美图源码

加速爬虫

传送门


   转载规则


《简单爬虫总结》 ZS 采用 知识共享署名 4.0 国际许可协议 进行许可。
  目录