xpath的高级应用

第一种

<button class="btn-check-phone click_btn" data-phone="1341243342334">查看联系方式</button>

匹配如下 '//*[text()="查看联系方式"]/@data-phone'

第二种

    <dl>
        <dt class="field-name">位置:</dt>
        <dd class="field-detail">
			<a>北京</a>
			<a class="region" >东城</a>
			<a class="region">东直门</a>
		</dd>
    </dl>

匹配//*[text()="位置:"]/following-sibling::dd[1]/a/text()
拼接 北京-东城-东直门
'-'.join([i for i in response.xpath('//*[text()="位置:"]/following-sibling::dd[1]/a/text()').extract()])

第三种

<div class="keyword-wrap">
    <strong class="">关键词:</strong>
    <strong class="keyword">信用贷款</strong>
    <strong class="keyword">不用什么抵押贷款</strong>
    <strong class="keyword">身份证贷款</strong>
</div>

匹配 //div[@class="keyword-wrap"]/strong[position()>1]/text()

xpath常用模式

翻页操作(一)

    next_url = response.xpath('//li[@class="next"]/a/@href').extract_first()
    if next_url is not None:
	    next_url = 'https://hr.tencent.com/' + next_url
	    yield scrapy.Request(url=next_url, callback=self.parse)

翻页操作(二)

   if 'javascript:;' not in next_url:
	  yield scrapy.Request(next_url, callback=self.parse)

遍历xpath列表的问题

常用清洗数据

    introduction = ''.join([i for i in response.xpath(u'//div[@class="content-wrap"]/text()').extract()]).replace('\t', '').replace('\xa0', '').replace('\n', '').replace('\u200c', '').replace(" ", '').strip()
    
    .replace('\t', '')   #\t 去横向跳到下一制表符位置
	.replace('\n', '')   #\n 去回车换行
	.replace('\u200c', '')  #\u200c 
	.replace(" ", '')     #" " 去空格
	.strip()              #去空格#strip()函数功能多样

-xpath 中的中文编码问题

u'//*[text()="位置:"]/following-sibling::dd[1]/a/text()

Scrapy终端 输出为ASCII

{'address': '\xe5\x8c\x97\xe47',
 'district': '\xe5\x8c\x97\'}
 
 scrapy可能在python2的环境上,Linux重新安装`pip3 install scrapy` 

匹配json,字典
类型如fjdgsdfgpoi{‘k1’: ‘v1’, ‘k2’: ‘v2’, ‘k3’: ‘v3’}asfdsfjkladsfjqleiifqe;oufperhnfu

Regular = re.compile('\{.*\}', re.S|re.M)
adaption = re.findall(Regular, str(receiveData))[0]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风华浪浪

讨个老婆本呗

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值