python抓取网页数据的三种方法
科技小能手 发布时间:2017-11-12 02:41:00 浏览7390 评论1摘要: 一、正则表达式提取网页内容 解析效率:正则表达式>lxml>beautifulsoup 代码: import re import urllib2 urllist = 'http://example.
一、正则表达式提取网页内容
解析效率:正则表达式>lxml>beautifulsoup
代码:
|
import re import urllib2
urllist = 'example.webscraping.com/places/defa…'
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 import urllib2
urllist = 'example.webscraping.com/places/defa…'
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 = 'example.webscraping.com/places/defa… 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 |
相关文章
- 《用Python写网络爬虫》——2.2 三种网页抓取方法
- 《用Python写网络爬虫》——第2章 数据抓取 2.…
- 50. Python 数据处理(1)
- 使用Scrapy抓取数据
- Python爬虫基础
- Python爬虫之BeautifulSoup
- 《用Python写网络爬虫》——导读
- 网络爬虫-原理篇(二)
- 如何仅使用内部链接策略来提高搜索排名
- 爬虫教程」Python做一个简单爬虫,小白也能看懂的教程