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···
相关文章推荐
- Python爬虫系列之----Scrapy(五)网页提取的三种方式(正则,Beautiful Soup,Lxml)
- python_urllib2下载网页的三种方式
- [Python]网络爬虫(一):抓取网页的含义和URL基本构成
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- python实现堆排序的三种方式
- Python目录遍历的三种方式
- 判断python对象是否可调用的三种方式及其区别
- [Python]网络爬虫(一):抓取网页的含义和URL基本构成
- Python 函数的三种定义方式
- 最简单的提升网页加载速度的三种方式
- Python网络爬虫(Get、Post抓取方式)
- [Python3.x]网络爬虫(三):urllib.request抓资源的方式总结
- python中list与tuple转化及三种小数取整方式
- 用Python写一个网络爬虫爬取网页中的图片
- Python网络爬虫(一)-----获取网页数据
- python爬虫:不同解析网页方式添加报头
- Python(11)—JavaScript弹出对话框的三种方式
- Python selenium 三种等待方式
- python 安装 easy_install 的三种方式
- [Python]网络爬虫(一):抓取网页的含义和URL基本构成