Python爬虫之抓取数据——正则表达式/Beautiful Soup/Lxml
来源:互联网 发布:多臂老虎机算法 编辑:程序博客网 时间:2024/05/19 00:42
有三种抓取网页中数据的方式:正则表达式,Beautiful Soup和lxml。
正则表达式
items = re.findall(regexp, str)
items = re.findall('<div.*?class="p-img">.*?<a.*?title="(.*?)".*?href="(.*?)".*?="//(.*?)".*?<div.*?class="p-price">.*?<i>(.*?)</i>', str_page, re.S)#(.*?)是希望抓取的数据。items是个列表,长度是匹配次数;items的元素本身也是个列表,长度是(.*?)出现的次数
Beautiful Soup
BeautifulSoup首先会把原始html(可能并不具备良好的HTML格式,比如缺少闭合标签)解析成具有良好HTML格式的html。
pip install beautifulsoup4
from bs4 import BeautifulSoupsoup = BeautifulSoup(old_html, 'html.parser')ul = soup.find('ul', attrs={'class':'country'})#返回第一个匹配lis = ul.find_all('li')#返回所有匹配lis[0].text
Lxml
Lxml模块使用C语言编写,解析速度比BeautifulSoup更快。Lxml和BeautifulSoup一样,首先会把html解析成正确格式。
import lxml.htmltree = lxml.html.fromstring(html)td = tree.cssselect('tr#places_area_row > td.w2p_fw')[0]#用CSS选择器选择元素area = td.text_content()
CSS选择器的模式:
通常情况下,Lxml是抓取数据最好的方式,快速又健壮。
性能对比
BeautifulSoup是用Python编写的,而re和Lxml都是用C实现的。BeautifulSoup比re和Lxml慢6倍左右。
阅读全文
0 0
- Python爬虫之抓取数据——正则表达式/Beautiful Soup/Lxml
- Python爬虫系列之----Scrapy(五)网页提取的三种方式(正则,Beautiful Soup,Lxml)
- Python网页抓取之Beautiful Soup
- Python爬虫实战一之使用Beautiful Soup抓取‘谣言百科’的分类内容
- Python爬虫实战一之使用Beautiful Soup抓取百度招聘信息并存储excel文件
- Python爬虫学习二——Beautiful Soup库
- Python网络爬虫——Beautiful Soup库
- 爬虫 Python爬虫利器二之Beautiful Soup的用法
- Python爬虫利器Beautiful Soup
- python爬虫利器--beautiful Soup
- Python爬虫入门八之Beautiful Soup的用法
- Python爬虫入门之Beautiful Soup的用法
- Python爬虫入门八之Beautiful Soup的用法
- Python爬虫入门八之Beautiful Soup的用法
- Python爬虫入门八之Beautiful Soup的用法
- Python爬虫利器二之Beautiful Soup的用法
- Python爬虫利器二之Beautiful Soup的用法
- Python爬虫利器二之Beautiful Soup的用法
- Python:输入一个数求它的最大约数。
- sql注入攻击
- 2017"百度之星"程序设计大赛
- 数据生成器
- LCATarjan离线算法
- Python爬虫之抓取数据——正则表达式/Beautiful Soup/Lxml
- httpclient
- Oracle 中number(P,S)函数的理解
- 微信小程序开发之服务器接口问题
- 比较strtr, str_replace和preg_replace三个函数的效率
- PHP报错类型及处理办法
- struts2漏洞中关于动态方法调用的一点思考
- UE4 Map 、Mode ---“project setting”中“Map&Mode”详讲 (随记系列1_项目设置)
- MyEclipse超级实用快捷键