用标题中的四种方式解析网页,比较其解析速度。当然比较结果数值与电脑配置,python版本都有关系,但总体差别不会很大。
下面是我的结果,lxml xpath最快,bs4最慢
==== Python version: 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] =====
==== Total trials: 10000 =====
bs4 total time: 5.5
pq total time: 0.9
lxml (cssselect) total time: 0.8
lxml (xpath) total time: 0.5
regex total time: 1.1 (doesn't find all p)
以下是测试代码
# -*- coding: utf-8 -*-
"""
@Datetime: 2019/3/13
@Author: Zhang Yafei
"""
import re
import sys
import time
import requests
from lxml.html import fromstring
from pyquery import PyQuery as pq
from bs4 import BeautifulSoup as bs
hea