用python写网络爬虫读书笔记 第二章数据抓取

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值