Bootstrap

Python -- 网络爬虫

Python – 网络爬虫

流程:
1. 连接链接获取页面内容(html文件);
2. 过滤获取需要信息(正则) [可能重复步骤1,2] ;
3. 存储文件到本地。

一)网络连接获取页面内容

# 网络连接获取页面内容es
import urllib.request as request # 使用网络请求类库
import urllib.error as error # 连接
import requests # 另一种网络连接方式

headers = {
    'Connection':'keep-alive',
    'Accept-Language':'zh-CN,zh;q=0.9',
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
}

# 简单直接访问网页 (某些网页可能被拒绝访问)
def getHtml(url):
    try:
        req = request.Request(url) # 获取请求
        webpage = request.urlopen(req) # 打开页面方法1
        # webpage = request.urlopen(url) # 打开页面方法2
    
        html = webpage.read() # 读取页面内容
        return html
    except error.URLError as e:
        print(str(e.code) + '\t' + e.reason)
        return None


def getXMLText(url):
    try:
        response = requests.get(url) # headers = headers
        response.raise_for_status()
        response.encoding = "utf-8"
        return response.text
    except:
        return None
    

# 配置访问请求
def getHtmlWithHead(url):
    req = request.Request(url, headers)  # 发送请求同时传data表单
    webpage = request.urlopen(req) 
    
    html = webpage.read() # 读取页面内容
    return html

#====================================================
def main():
    url = input('输入网址: ')
    print(getHtml(url))
    print(getXMLText(url))
        
#----------------------------------------------------------------
if __name__ == '__main__':
    main()
python用于爬虫的库: urllib, requests

urllib.request 用于打开和读取URL, (request.urlopen)
urllib.error 用于处理前面request引起的异常, (:403	Forbidden)
urllib.parse 用于解析URL,

urlopen(url, data=None, timeout=<object object at 0x000001D4652FE140>, *, cafile=None, capath=None, cadefault=False, context=None)。

二)过滤、筛选、替换

1. from bs4 import BeautifulSoup as bs: # 使用文档解析类库, 整理HTML文件,方便处理
soup = bs(html, 'html.parser') # 'lxml'

# 返回为数组
info = soup.find_all('div', attrs={'class' : 'add'})# 获取所有标签为'div', 属性为class,属性值为'add'的数据: <div class="add">当前位置:xxxx</div>
info = soup.select('p') # 获取所有标签为'a'(链接)的数据:<a href="https://www.xxx.com/">xxx</a>

2. import re # 正则

# 返回为数组
title = re.compile(r'<h2>(.*?)</h2>').search(str(info))# 在info字符串内获取所有被<h2>和</h2>包围的字段
3. str 字符操作
author = str(info).replace('<p>','').replace('</p>','').rstrip() # lstrip()

三)本地存储

import os # 含文件读写
import time # time.sleep(0.1)

dir = 'D:\\Python\\Data\\'
path = 'D:\\Python\\Data\\text.txt'
1. create dir
isExists = os.path.exists(dir)
    if not isExists:
        os.mkdir(path)
        
2. write: 'w','wb'
file = open(path,'w',encoding='utf-8') # 以'utf-8'编码方式向path路径指向的文件内写入(不存在会自动创建)
file.write('content')
file.close() # 写完后记得关闭

3. read: 'r','rb'
file = open(path, 'rb')
;