1.前言
1.1 抓取网页
本文将举例说明抓取网页数据的三种方式:正则表达式、BeautifulSoup、lxml。
获取网页内容所用代码详情请参照Python网络爬虫-你的第一个爬虫。利用该代码获取抓取整个网页。
import requests
def download(url, num_retries=2, user_agent='wswp', proxies=None):
'''下载一个指定的URL并返回网页内容
参数:
url(str): URL
关键字参数:
user_agent(str):用户代理(默认值:wswp)
proxies(dict): 代理(字典): 键:‘http’'https'
值:字符串(‘http(s)://IP’)
num_retries(int):如果有5xx错误就重试(默认:2)
#5xx服务器错误,表示服务器无法完成明显有效的请求。
#https://zh.wikipedia.org/wiki/HTTP%E7%8A%B6%E6%80%81%E7%A0%81
'''
print('==========================================')
print('Downloading:', url)
headers = {'User-Agent': user_agent} #头部设置,默认头部有时候会被网页反扒而出错
try:
resp = requests.get(url, headers=headers, proxies=proxies) #简单粗暴,.get(url)
html = resp.text #获取网页内容,字符串形式
if resp.status_code >= 400: #异常处理,4xx客户端错误 返回None
print('Download error:', resp.text)
html = None
if num_retries and 500 <= resp.status_code < 600:
# 5类错误
return download(url, num_retries - 1)#如果有服务器错误就重试两次
except requests.exceptions.RequestException as e: #其他错误,正常报错
print('Download error:', e)
html = None
return html #返回html
1.2 爬取目标
爬取http://example.webscraping.com/places/default/view/Australia-14网页中所有显示内容。
分析网页结构可以看出,所有内容都在标签
根据这个结构,我们用不同的方式来表达,就可以抓取到所有想要的数据了。
| 7,686,850 square kilometres |
#正则表达式:
re.search(r'<tr id="places_area__row">.*?<td class="w2p_fw">(.*?)</td>').groups()[0] # .*?表示任意非换行值,()是分组,可用于输出。
#BeautifulSoup
soup.find('table').find('tr', id='places_area__row').find('td', class_="w2p_fw").text
#lxml_css selector
tree.cssselect('table > tr#places_area__row > td.w2p_fw' )[0].text_content()
#lxml_xpath
tree.xpath('//tr[@id="places_area__row"]/td[@class="w2p_fw"]' )[0].text_content()
Chrome 浏览器可以方便的复制出各种表达方式:

有了以上的download函数和不同的表达式,我们就可以用三种不同的方法来抓取数据了。
2.不同方式抓取数据
2.1 正则表达式爬取网页
正则表达式不管在python还是其他语言都有很好的应用,用简单的规定符号来表达不同的字符串组成形式,简洁又高效。学习正则表达式很有必要。https://docs.python.org/3/howto/regex.html。 python内置正则表达式,无需额外安装。
import re
targets = ('area', 'population', 'iso', 'country', 'capital', 'continent',
'tld', 'currency_code', 'currency_name', 'phone', 'postal_code_format',
'postal_code_regex', 'languages', 'neighbours')
def re_scraper(html):
results = {}
for target in targets:
results[target] = re.search(r'<tr id="places_%s__row">.*?<td class="w2p_fw">(.*?)</td>'
% target, html).groups()[0]
return results
2.2BeautifulSoup抓取数据
BeautifulSoup用法可见python 网络爬虫 - BeautifulSoup 爬取网络数据
代码如下:
from bs4 import BeautifulSoup
targets = ('area', 'population', 'iso', 'country', 'capital', 'continent',
'tld', 'currency_code', 'currency_name', 'phone', 'postal_code_format',
'postal_code_regex', 'languages', 'neighbours')
def bs_scraper(html):
soup = BeautifulSoup(html, 'html.parser')
results = {}
for target in targets:
results[target] = soup.find('table').find('tr', id='places_%s__row' % target) \
.find('td', class_="w2p_fw").text
return results
2.3 lxml 抓取数据
from lxml.html import fromstring
def lxml_scraper(html):
tree = fromstring(html)
results = {}
for target in targets:
results[target] = tree.cssselect('table > tr#places_%s__row > td.w2p_fw' % target)[0].text_content()
return results
def lxml_xpath_scraper(html):
tree = fromstring(html)
results = {}
for target in targets:
results[target] = tree.xpath('//tr[@id="places_%s__row"]/td[@class="w2p_fw"]' % target)[0].text_content()
return results
2.4 运行结果
scrapers = [('re', re_scraper), ('bs',bs_scraper), ('lxml', lxml_scraper), ('lxml_xpath',lxml_xpath_scraper)]
html = download('http://example.webscraping.com/places/default/view/Australia-14')
for name, scraper in scrapers:
print(name,"=================================================================")
result = scraper(html)
print(result)
==========================================
Downloading: http://example.webscraping.com/places/default/view/Australia-14
re =================================================================
{'area': '7,686,850 square kilometres', 'population': '21,515,754', 'iso': 'AU', 'country': 'Australia', 'capital': 'Canberra', 'continent': '<a href="/places/default/continent/OC">OC</a>', 'tld': '.au', 'currency_code': 'AUD', 'currency_name': 'Dollar', 'phone': '61', 'postal_code_format': '####', 'postal_code_regex': '^(\\d{4})$', 'languages': 'en-AU', 'neighbours': '<div><a href="/places/default/iso//"> </a></div>'}
bs =================================================================
{'area': '7,686,850 square kilometres', 'population': '21,515,754', 'iso': 'AU', 'country': 'Australia', 'capital': 'Canberra', 'continent': 'OC', 'tld': '.au', 'currency_code': 'AUD', 'currency_name': 'Dollar', 'phone': '61', 'postal_code_format': '####', 'postal_code_regex': '^(\\d{4})$', 'languages': 'en-AU', 'neighbours': ' '}
lxml =================================================================
{'area': '7,686,850 square kilometres', 'population': '21,515,754', 'iso': 'AU', 'country': 'Australia', 'capital': 'Canberra', 'continent': 'OC', 'tld': '.au', 'currency_code': 'AUD', 'currency_name': 'Dollar', 'phone': '61', 'postal_code_format': '####', 'postal_code_regex': '^(\\d{4})$', 'languages': 'en-AU', 'neighbours': ' '}
lxml_xpath =================================================================
{'area': '7,686,850 square kilometres', 'population': '21,515,754', 'iso': 'AU', 'country': 'Australia', 'capital': 'Canberra', 'continent': 'OC', 'tld': '.au', 'currency_code': 'AUD', 'currency_name': 'Dollar', 'phone': '61', 'postal_code_format': '####', 'postal_code_regex': '^(\\d{4})$', 'languages': 'en-AU', 'neighbours': ' '}
从结果可以看出正则表达式在某些地方返回多余元素,而不是纯粹的文本。这是因为这些地方的网页结构和别的地方不同,因此正则表达式不能完全覆盖一样的内容,如有的地方包含链接和图片。而BeautifulSoup和lxml有专门的提取文本函数,因此不会有类似错误。
既然有三种不同的抓取方式,那有什么区别?应用场合如何?该如何选择呢?
3. 爬虫性能对比
上面的爬虫由于爬取数据量有限,因此无法对比它们的性能。接下来将对比它们爬取大量数据时的性能。
目标:爬取网页所有显示内容,重复1000次,比较不同爬虫的爬取时间。
准备:导入网页爬取函数download,导入所有爬虫。
开始coding:
import time
import re
from chp2_all_scrapers import re_scraper, bs_scraper, lxml_scraper, lxml_xpath_scraper
from chp1_download import download
num_iterations = 1000 # 每个爬虫测试1000次
html = download('http://example.webscraping.com/places/default/view/Australia-14')
scrapers = [('re', re_scraper), ('bs', bs_scraper), ('lxml', lxml_scraper),
('lxml_xpath', lxml_xpath_scraper)]
for name, scraper in scrapers:
start_time = time.time()
for i in range(num_iterations):
if scraper == re_scraper:
re.purge() #清除缓存,保证公平性
result = scraper(html)
# 检测结果是否为想要的
assert result['area'] == '7,686,850 square kilometres'
end_time = time.time()
print("=================================================================")
print('%s: %.2f seconds' % (name, end_time - start_time))
注意:re.purge() 是为了清除缓存。因为正则表达式默认情况下会缓存搜索,需要对其清除以保证公平性。如果不清除缓存,后面的999次都是在作弊,结果惊人!
运行结果:
Downloading: http://example.webscraping.com/places/default/view/Australia-14
=================================================================
re: 2.40 seconds
=================================================================
bs: 18.49 seconds
=================================================================
lxml: 3.82 seconds
=================================================================
lxml_xpath: 1.53 seconds
Process finished with exit code 0
#作弊结果
Downloading: http://example.webscraping.com/places/default/view/Australia-14
=================================================================
re: 0.19 seconds
=================================================================
bs: 18.12 seconds
=================================================================
lxml: 3.43 seconds
=================================================================
lxml_xpath: 1.50 seconds
Process finished with exit code 0
从结果可以明显看出正则表达式和lxml的性能差不多,采用xpath性能最佳,BeautifulSoup性能最差! 因为BeautifulSoup是纯python写的而lxml是c写的,性能可见一斑。
绝大部分网上教程都在使用BeautifulSoup写爬虫,这是因为BeautifulSoup可读性更高,更加人性,而css selector 和xpath需要学习他们特有的表达方式,但是绝对值得学习的。性能提高不止十倍(相对)!
4.结论
| 爬取方式 | 性能 | 易用性 | 易安装性 |
|---|---|---|---|
| 正则表达式 | 快 | 难 | 内置 |
| BeautifulSoup | 慢 | 易 | 易 |
| lxml | 快 | 易 | 偏难 |
因此在爬取少量数据时,BeautifulSoup可以胜任,而且易读性高,但是大量数据采集时就建议使用lxml。
本文介绍了Python爬虫抓取网页数据的三种方式:正则表达式、BeautifulSoup和lxml,并通过对比分析得出在大量数据采集时,lxml的性能优于BeautifulSoup,推荐在需要高性能爬虫时使用。


被折叠的 条评论
为什么被折叠?



