您的位置:首页 > 理论基础 > 计算机网络

python网络爬虫-爬取网页的三种方式(1)

2018-03-07 00:15 337 查看

0.前言

0.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


0.2 爬取目标

爬取http://example.webscraping.com/places/default/view/Australia-14网页中所有显示内容。



分析网页结构可以看出,所有内容都在标签
中,以area为例可以看出,area的值在:

根据这个结构,我们用不同的方式来表达,就可以抓取到所有想要的数据了。
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").t
bd1e
ext
#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函数和不同的表达式,我们就可以用三种不同的方法来抓取数据了。

1.不同方式抓取数据

1.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


1.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


1.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


1.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有专门的提取文本函数,因此不会有类似错误。

既然有三种不同的抓取方式,那有什么区别?应用场合如何?该如何选择呢?

···to be continued···
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: