Python--通过XPath实现网络爬虫
2016-11-10 21:39
543 查看
安装lxml流程
首先通过下载lxml从中选择适合你的电脑的版本。一般包含Python版本和电脑版本。下载很慢,但是下载好之后是lxml-3.5.0-cp27-none-win_amd64.whl(Python2.7、64位Windows10)文件
我的方法是将该文件放到D:\Software\Python2.7\Scripts安装文件的目录下,然后打开命令行,进入到该目录下再输入命令 pip install lxml-3.5.0-cp27-none-win_amd64.whl 然后就可以了
XPath
XPath是一门语言XPath可以在XML文档中查找信息
XPath支持HTML
XPath通过元素和属性进行导航
XPath可以用来提取信息
XPath比正则表达式厉害
XPath比正则表达式简单
流程
安装lXML第三方库from lxml import etree
selector = etree.HTML(网页源代码)
selector.xpath(神秘的代码)
简介
//:定位根节点/:往下层寻找
/text():提取文本内容
/@xxxx:提取属性内容
例子
#-*-coding:utf8-*- from lxml import etree html = ''' <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>测试-常规用法</title> </head> <body> <div id="content"> <ul id="useful"> <li>这是第一条信息</li> <li>这是第二条信息</li> <li>这是第三条信息</li> </ul> <ul id="useless"> <li>不需要的信息1</li> <li>不需要的信息2</li> <li>不需要的信息3</li> </ul> <div id="url"> <a href="http://yuanlief.com">此间少年</a> <a href="http://yuanlief.com/course/" title="似水流年">点我打开</a> </div> </div> </body> </html> ''' selector = etree.HTML(html) #提取文本 # content = selector.xpath('//ul[@id="useful"]/li/text()') # for each in content: # print each #输出:这是第一条信息 #输出:这是第二条信息 #输出:这是第三条信息 #------------------------------------------------------------------- #提取属性 # # link = selector.xpath('//div[@id="url"]/a/@href') # for each in link: # print each #输出http://yuanlief.com和http://yuanlief.com/course/ #------------------------------------------------------------------- #title = selector.xpath('//a/@title') #print title[0]#输出此间少年
相关文章推荐
- python实现网络爬虫
- Python实现网络爬虫
- python网络爬虫——基本概念及代码实现1
- 聚焦网络爬虫之Xpath+HttpClient快速实现页面新闻抓取
- C#使用多线程实现网络爬虫,并且通过网络传输,传到另外的服务器数据库存储
- python实现网络爬虫
- Python 实现网络爬虫小程序
- python 实现简单网络爬虫
- Python实现网络爬虫
- 使用requests+beautifulsoup模块实现python网络爬虫功能
- [Python] 实现网络爬虫
- [Python] 实现网络爬虫
- python实现网络爬虫学习总结
- python实现简易网络爬虫
- Python实现网络爬虫
- python实现网络爬虫
- python使用rabbitmq实现网络爬虫示例
- Python 网络爬虫5 ---- 第一次实现抓取数据并且存放到mysql数据库中
- 网络资源搜索爬虫(python 3.4.1实现)
- python实现网络爬虫