爬虫能够爬取得到更规整的数据(split模块)

其实大家用过下request爬虫就会发现

其实各网站的html语言并不能做到完全统一

这就会导致使用xpath爬取的时候

会出现一些杂乱字符

例如“\n","\t"之类的

即使xpath写的非常好这种情况也是很难避免的

此时让我们用一个网站来举例

 某采购网https://search.ccgp.gov.cn/bxsearch?searchtype=1&page_index=1&bidSort=0&buyerName=&projectId=&pinMu=0&bidType=0&dbselect=bidx&kw=%E6%B5%8B%E7%BB%98&start_time=2022%3A07%3A27&end_time=2022%3A08%3A03&timeType=2&displayZone=&zoneId=&pppStatus=0&agentName=

我在使用xpath模块进行爬取标题的时候

源码如下

import requests # python基础爬虫库
from lxml import etree # 可以将网页转换为
import time
import datetime
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36'}
title_list=[]
web='https://search.ccgp.gov.cn/bxsearch?searchtype=1&page_index=1&bidSort=0&buyerName=&projectId=&pinMu=0&bidType=0&dbselect=bidx&kw=%E6%B5%8B%E7%BB%98&start_time=2022%3A07%3A27&end_time=2022%3A08%3A03&timeType=2&displayZone=&zoneId=&pppStatus=0&agentName='
response2 = requests.get(url=web,headers=headers) 
response2.encoding = 'utf-8'
wb_data2 = response2.text
html = etree.HTML(wb_data2)
title_list=title_list+html.xpath('//div[5]/div[2]/div/div/div[1]/ul/li/a[@href]/text()')
    

爬取出来的东西有乱码

出来的数据大概长这样

一般常规来讲爬取的信息出现这种乱码字符,有三种解决方式

  1. 精修xpath模块
  2. 加载re正则表达模块,使用正则表达模块进行数据处理
  3. 就是使用split在爬取时进行处理

这三种方法各有优劣

 这篇文章文章着重分析split的使用

(准备插两个传送门)

首先明确概念,

string.split(s[, sep[, maxsplit]]),针对string类型的split()函数。

它主要是切割字符串,结果返回由字符串元素组成的一个列表。

举例说明:

 因为xpath爬取的数据往往天生就是一个列表形式(真的你信我)

所以我们在用split处理杂乱数据之前,往往需要使用

str()函数

将list形式的数据转化为str形式(如上图所示)

然后通过

 title_list=title_list+[str(html.xpath('//div[5]/div[2]/div/div/div[1]/ul/li['+str(i)+']/a[@href]/text()')).split("\\r\\n                                        ")[1].split("\\r\\n")[0]]

就可以啦

记得遍历哦

详细代码

参见

爬虫实践:陕西招投标爬虫(三个网站)xpath封装并exe_向高数吹起最后的冲锋号角的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/weixin_48572116/article/details/126138805
今日推荐