Python 爬虫案例(六)

287次阅读
没有评论

一个很简单的问题:xpath定位不到想要得到的数据,实际上就是我们表面上看到的网页格式并不是真实的网页格式,举例说明:点击查看网页 这个网页,先建立好爬虫项目,起好爬虫的名字,这里爬虫名字就为:test.py.

用google浏览器打开链接,右击检查,然后Ctrl+F键,找到我们像定位的地方,进行定位搜索:“//*[@id=‘menu’]/following-sibling::table/tbody/tr[2]/@onclick”
Python
可以看到,已经找到了定位信息,然后再test.py中进行编写:

import scrapy

class KeywordSpider(scrapy.Spider): name = 'test' start_urls = ['https://xxgk.eic.sh.cn/jsp/view/eiaReportList.jsp']

def parse(self, response): result_list = response.xpath("//*[@id='menu']/following-sibling::table/tbody/tr[2]/@onclick") print(result_list)

记得把setting.py里面的设置改一下“ROBOTSTXT_OBEY = False”
然后scrapy crawl test执行一下,结果没有爬取到任何东西:
Python

原因是:xpath定位不对,不能光看数据在浏览器中的定位,可以先返回response.body看一下具体是什么情况:

import scrapy

class KeywordSpider(scrapy.Spider): name = 'test' start_urls = ['https://xxgk.eic.sh.cn/jsp/view/eiaReportList.jsp']

def parse(self, response): print(str(response.body,encoding="utf-8")) # result_list = response.xpath("//*[@id='menu']/following-sibling::table/tbody/tr[2]/@onclick") # print(result_list)

执行一下,发现是可以抓到东西的:
Python

这就证实了是xpath定位的不对,我们在爬虫爬到的数据中找到原来我们想定位的地方,发现table下面下一个节点根本没有tbody:
Python

接下来更改一下test.py的脚本代码:

import scrapy

class KeywordSpider(scrapy.Spider): name = 'test' start_urls = ['https://xxgk.eic.sh.cn/jsp/view/eiaReportList.jsp']

def parse(self, response): result_list = response.xpath("//*[@id='menu']/following-sibling::table/tr[2]/@onclick") print(result_list)

现在就可以抓到东西了:
Python

所以以后爬东西,先把response.body爬下来,再去做精准的定位!

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:Python教程2022-10-28发表,共计1419字。
新手QQ群:570568346,欢迎进群讨论 Python51学习