天天看點

python抓取網頁資料的三種方法

一、正規表達式提取網頁内容

解析效率:正規表達式>lxml>beautifulsoup

代碼:

import  re

import  urllib2

html =  urllib2.urlopen(urllist).read()

num =  re.findall('<td class="w2p_fw">(.*?)</td>',html)

print  num

print  "num[1]: ",num[1]

二、BeautifulSoup方法提取網頁内容

代碼如下:

from  bs4 import BeautifulSoup

#把html格式進行确定和糾正

soup =  BeautifulSoup(html,'html.parser')

#找出tr标簽中id屬性為places_area__row的内容,如果把find改成findall函數則會把比對所#有的内容顯示出來,find函數隻比對第一次比對的内容。

tr =  soup.find('tr',attrs={'id':'places_area__row'})

td =  tr.find('td',attrs={'class':'w2p_fw'})

#取出标簽内容

area =  td.text

print  "area: ",area

三、lxml

lxml庫功能和使用類似BeautifulSoup庫,不過lxml解析速度比beautifulsoup快。

import  lxml.html

w/United-Kingdom-239'

tree =  lxml.html.fromstring(html)

td =  tree.cssselect('tr#places_area__row > td.w2p_fw')[0]

area =  td.text_content()

print  area

本文轉自 老鷹a  51CTO部落格,原文連結:http://blog.51cto.com/laoyinga/1939999