python requests爬虫使用lxml解析HTML获取信息不对等的问题

版权声明: https://blog.csdn.net/qq_40244755/article/details/83105339

python requests爬虫使用lxml解析HTML获取信息不对等的问题

我们在用lxml解析HTML文本时,有时会碰到“<”p“>”标签有换行“<“br”>”的情况,如果我们用获取xpath的方法,循环获得该元素下的所有text()文本,同一个“<”p“>”标签会出现两段内容,解决办法是替换掉网页文本内容:

	#!/usr/bin/env python
	# -*- coding:utf-8 -*-
	# Author pudding
	import requests
	from lxml import etree
	
	url = 'http://******'
    data = requests.get(url)
    r = data.content
    html_doc = str(r, 'utf-8')   # 此举旨在正确编码,避免乱码 
    s = etree.HTML(html_doc.read().replace('<br>', '').replace('</br>', ''))

这样便可达到目的。

 phone = s.xpath('//*[@id="content"]/table//text()')
 for index, ph in enumerate(phone):
 	if index > 0:
    	sheet_one.write(index + 1, 3, str(ph))

猜你喜欢

转载自blog.csdn.net/qq_40244755/article/details/83105339