最近在使用xpath提取信息时,由于所提取页面的数据标签比较凌乱,我只想要获取页面所显示的文本信息,因此通过查询相关资料,总结出如下方法:
1.获取文本值及所有html标签
html_content3 = requests.get(details_url).text
html = etree.HTML(html_content3)
# content=html.xpath('//div[@class="article-entry"]')[0].xpath('string(.)').strip()#得到其中的所有文本信息,但没有了标签属性。
# 先取出包含文章主体的标签
contents = html.xpath('//div[@class="article-entry"]')[0]
# 取出来的是个element对象,需要给他转换成字符串
name1 = etree.tostring(contents, method='html')
# 转成字符串后中文不能正常显示,需要再对其进行解析
name2 = HTMLParser().unescape(name1.decode())
content = name2
2.只获取文本值
welfare = response.xpath('//div[@class="t1"]').xpath('string(.)').extract()[0]
或者
welfare = response.xpath('//div[@class="t1"]').xpath('string(.)').extract()[0]
注意:如果使用element来获取,会遇到extract属性不存在的错误可以将其改为如下代码:
welfare = response.xpath('//div[@class="t1"]').xpath('string(.)').strip()