一、正则表达式提取网页内容
解析效率:正则表达式>lxml>beautifulsoup
代码:
',html)
print num
print "num[1]: ",num[1]
import re import urllib2
urllist = 'http://example.webscraping.com/places/default/view/United-Kingdom-239'
html = urllib2.urlopen(urllist).read() num = re.findall(' |
(.*?) |
二、BeautifulSoup方法提取网页内容
代码如下:
from bs4 import BeautifulSoup import urllib2
urllist = 'http://example.webscraping.com/places/default/view/United-Kingdom-239'
html = urllib2.urlopen(urllist).read() #把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 import urllib2
urllist = 'http://example.webscraping.com/places/default/vie w/United-Kingdom-239'
html = urllib2.urlopen(urllist).read() 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