python xpath lxml调试

1
2
3
4
5
6
7
8
9
10
11
<li>
<a href="/Н">Н</a>:<a class="det" href='/view/Н/ньютон'>ньютон</a>
 【物理】牛顿(力单位)
<div class="satis" style="display:none">
<span>您对本词条的内容满意吗:</span>
<font>
<a href="###" tip-data="good" updateword="ньютон" satis="245057">满意</a>
<a href="###" tip-data="update" updateword="ньютон" satis="2">请改进</a>
</font>
</div>
</li>

遇到此段xml需要处理,查了些资料,现解决如下:

1
2
3
4
5
6
7
8
9
10
11
12
def readFile(filen,decoding): 
    html = '' 
    try
        html = open(filen).read().decode(decoding) 
    except
        pass 
    return html 
   
def extract(file,decoding, xpath): 
    html = readFile(file, decoding) 
    tree = etree.HTML(html)
    return tree.xpath(xpath)

两个函数,用于解决读取中文网页时出现的编码问题。


1
2
3
4
5
6
7
8
9
10
11
12
def GetXpath1(url,xpath,saveFile):
    response=urllib2.urlopen(url)
    data=response.read()
    f=file("temp.txt",'w')   
    f.write(data)
    f.close()
    sections = extract('temp.txt', 'utf-8', xpath)
    print len(sections),type(sections)#输出1 <type 'list'>
    print sections#此处为元素[<Element a at 0x26c8948>]
    print sections[0].tag,sections[0].attrib,sections[0].attrib.get("href")
    #输出a {'href': u'/view/\u041d/\u041d\u043e\u0432\u0433\u043e\u0440\u043e\u0434', 'class': 'det'} /view/Н/Новгород
    print type(sections[0].attrib)#<type 'lxml.etree._Attrib'>

此处关键地方,花了些时间解决,主要是为了提取

<li><a href="/Н">Н</a>:<a class="det" href='/view/Н/ньютон'>ньютон</a>

中的俄语,需要注意的是Element的属性tag, attrib,get("")的使用

到此基本就获取需要东西了

转载于:https://www.cnblogs.com/findeasy/p/4053092.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值