您的位置:首页 > 编程语言 > Python开发

Python 爬虫学习笔记二: xpath 模块

2017-11-14 16:27 691 查看

Python 爬虫学习笔记二: xpath from lxml

首先应该知道的是xpath 只是一个元素选择器, 在python 的另外一个库lxml 中, 想要使用xpath 必须首先下载lxml 库

lxml 库的安装: 很简单, 具体请查看 http://www.jianshu.com/p/2bc5aa0db486

上述链接中有如何安装lxml , 以及如何使用xpath的入门程序, 以及xpath 的初始语法

pip install lxml


初始实践的code 记录:

from lxml import etree
import requests
url = 'http://sh.lianjia.com/ershoufang/'
region = 'pudong'
finalURL = url+region
price = 'p23'
r= requests.get(finalURL)
r.text
html = requests.get(finalURL).content.decode('utf-8')
dom_tree = etree.HTML(html)
links = dom_tree.xpath("//div/span[@class='info-col row2-text']/a")

for i in links:
print(i.text)

links_yaoshi = dom_tree.xpath("//div/span[@class='c-prop-tag2']")

for i in links_yaoshi:
print(i.text)

links_danjia = dom_tree.xpath("//span[@class='info-col price-item minor']")

for index in range(len(links_yaoshi)):
print(index)
print(links[index].text)
print(links_yaoshi[index].text)
print(links_danjia[index].text)


本来想要将这些不同标签下的信息分别取出,在打印的时候再将信息进行合并, 但是输出的结果格式不符合标准并且爬出的element数量不一致导致代码报错。

一定注意 xpath 查找提取结果是可以用“|”来提取多个results, 所以最终的code 如下:

from lxml import etree
import requests
url = 'http://sh.lianjia.com/ershoufang/'
region = 'pudong'
finalURL = url+region
price = 'p23'
r= requests.get(finalURL)
r.text
html = requests.get(finalURL).content.decode('utf-8')
dom_tree = etree.HTML(html)
"""
links = dom_tree.xpath("//div/span[@class='info-col row2-text']/a")

for i in links:
print(i.text)

links_yaoshi = dom_tree.xpath("//div/span[@class='c-prop-tag2']")

for i in links_yaoshi:
print(i.text)

links_danjia = dom_tree.xpath("//span[@class='info-col price-item minor']")

for index in range(len(links_yaoshi)):
print(index)
print(links[index].text)
print(links_yaoshi[index].text)
print(links_danjia[index].text)
"""
data = dom_tree.xpath("//div[@class='info-table']/text()")
# info = data[0].xpath('string(.)').extract()[0]

dataRes = dom_tree.xpath("//div/span[@class='info-col row2-text']/a | //div/span[@class='c-prop-tag2'] | //span[@class='info-col price-item minor']")

for i in dataRes:
print(i.text)


打印出的结果:



3 . 写代码的时候, 有时会输出形如< Element a at 0x334fcb0> 的结果, 这个是pyhton 中的一个对象,表示的是element a 存储的物理内存地址。

4. 想取出element 之间的内容, 形如下图中红色方框中的内容:



但是使用如下命令的时候:

# 取出element之间的内容
bloger = dom_tree.xpath("//div[@class='info-table']")
#"info-table" 是截屏中DOM 结构的上两级的element , <div class="info-table">
print (bloger[0].xpath('string(.)').strip())


输出结果是整个div 下面所有的text 文本(有点小惊喜)



致谢这篇文章: http://www.jianshu.com/p/4f29a4cfbbb3

5 . 所以我想要取出所有的text文本的话,可以直接截取< li> ,或者使用 | 筛查出另外的信息



最终取出所有结果的code :

# all the messages
all_message = dom_tree.xpath("//ul[@class='js_fang_list']/li")
print (all_message[0].xpath('string(.)').strip())  # 只是打印第一行的结果

for index in range(len(all_message)):
print(all_message[index].xpath('string(.)').strip())


最终的输出结果示例:



至此,单页爬虫以及相应text 文本的输出就告一段落。

【注】Python 及 xpath 应用 :

XPATH 查找指定Class 元素 :

https://jingyan.baidu.com/article/a65957f49427aa24e77f9b56.html

Pyhton 单行、多行注释符号使用方法及规范 http://www.iplaypy.com/jichu/note.html

Python中字符串string操作 : https://www.cnblogs.com/hongten/p/hongten_python_string.html

xpath提取某个路径下面的所有符合条件的text 文本 ,请参考:

https://www.cnblogs.com/xieqiankun/p/xpath_extract_text.html?utm_source=tuicool&utm_medium=referral

http://blog.csdn.net/MrLevo520/article/details/53158050

这个文章中有关于提取文本中的错误纠正,但是后来我试用之后仍然不work , 原因是我的python版本是 3.X

xpath 介绍的比较详细的语法信息: http://cuiqingcai.com/2621.html

Python爬虫利器三之Xpath语法与lxml库的用法 : http://cuiqingcai.com/2621.html

xpath定位中starts-with、contains和text()的用法: http://blog.csdn.net/zhouxuan623/article/details/43935039

解决:xpath取出指定多标签内所有文字text : http://www.jianshu.com/p/4f29a4cfbbb3

知乎的这个关于python 的帖子写的实在是真的不错 : https://www.zhihu.com/question/27621722

b9d7
知乎,如何利用爬取的数据来赚钱: https://www.zhihu.com/question/53211864

【附】最终的Fang.py 文件 :

from lxml import etree
import requests
url = 'http://sh.lianjia.com/ershoufang/'
region = 'pudong'
finalURL = url+region
price = 'p23'
r= requests.get(finalURL)
r.text
html = requests.get(finalURL).content.decode('utf-8')
dom_tree = etree.HTML(html)
"""
links = dom_tree.xpath("//div/span[@class='info-col row2-text']/a")

for i in links:
print(i.text)

links_yaoshi = dom_tree.xpath("//div/span[@class='c-prop-tag2']")

for i in links_yaoshi:
print(i.text)

links_danjia = dom_tree.xpath("//span[@class='info-col price-item minor']")

for index in range(len(links_yaoshi)):
print(index)
print(links[index].text)
print(links_yaoshi[index].text)
print(links_danjia[index].text)
"""
data = dom_tree.xpath("//div[@class='info-table']/text()")

# 取出element之间的内容
bloger = dom_tree.xpath("//div[@class='info-table']")
print (bloger[0].xpath('string(.)').strip())

# all the messages all_message = dom_tree.xpath("//ul[@class='js_fang_list']/li") print (all_message[0].xpath('string(.)').strip()) # 只是打印第一行的结果 for index in range(len(all_message)): print(all_message[index].xpath('string(.)').strip())

print(dom_tree.xpath("//*[@id='js-ershoufangList']/div[2]/div[3]/div[1]/ul/li[1]/div/div[2]/div[1]/span")[0].xpath('string(.)').strip())

# info = data[0].xpath('string(.)').extract()[0]
data_fangxing = dom_tree.xpath("//div/div[2]/div[1]/span[@class='info-col row1-text']/text()")
#results = etree.tostring(data_fangxing.pop, pretty_print=True)

#results = etree.tostring(data_fangxing.pop(0), pretty_print=True)
#print(results)

dataRes = dom_tree.xpath("//div/span[@class='info-col row2-text']/a | //div/div[2]/div[1]/span[@class='info-col row1-text'] | //div/span[@class='c-prop-tag2'] | //span[@class='info-col price-item minor']")

#for i in dataRes:

# print(i.text)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 爬虫 xpath