1 三种网页抓取方法
1.1 正则表达式
通过分析网页可以看到多个国家的属性都使用了<td class="w2p_fw">标签,例如国家面积属性的位置:
这样就可以通过正则表达式进行数据的抓取:
# -*- coding: utf-8 -*-
import urllib2
import re
def scrape(html):
area = re.findall('<tr id="places_area__row"><td class="w2p_fl"><label class="readonly" for="places_area" id="places_area__label">Area: </label></td><td class="w2p_fw">(.*?)</td><td class="w2p_fc"></td></tr>', html)[0]
return area
if __name__ == '__main__':
html = urllib2.urlopen('http://example.webscraping.com/places/default/view/Afghanistan-1').read()
print scrape(html)
但是如果网页发生变化,这种方案很容易失效。
1.2 Beautiful Soup
首先安装beautifulsoup4
pip install beautifulsoup4
使用beautifulsoup的第一步就是将已经下载的HTML内容解析为soup文档。此外beautifulsoup还具有修补引号缺失和标签未闭合的问题。
from bs4 import BeautifulSoup
broken_html='<ul class=country><li>Area<li>Population</ul>'
soup=BeautifulSoup(broken_html,'html.parser')
fixed_html=soup.prettify()
print fixed_html
ul=soup.find('ul',attrs={'class':'country'})
li=ul.find('li')
print li.text
print ul.find_all('li')
print soup.li.li.string
输出结果为:
<ul class="country">
<li>
Area
<li>
Population
</li>
</li>
</ul>
AreaPopulation
[<li>Area<li>Population</li></li>, <li>Population</li>]
Population
1.3 Lxml
lxml同样具有修补网页标签的能力
import lxml.html
broken_html='<ul class=country><li>Area<li>Population</ul>'
tree=lxml.html.fromstring(broken_html)
fixed_html=lxml.html.tostring(tree, pretty_print=True)
print fixed_html
输出结果为:
<ul class="country">
<li>Area</li>
<li>Population</li>
&l