python - 我写的Xpath 为什么爬取不到内容
本文介绍了python - 我写的Xpath 为什么爬取不到内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
-- coding:utf-8 --
import lxml,requests,sys
from bs4 import BeautifulSoup
from lxml import etree
reload(sys)
sys.setdefaultencoding("utf-8")
def main():
url = 'https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=%E6%9A%B4%E8%B5%B0%E6%BC%AB%E7%94%BB&pn=0'
req = requests.get(url).content
# soup = BeautifulSoup(req.content,'lxml')
# imgs = soup.find_all('img')
content = etree.HTML(req)
paths = content.xpath('//*[@id="imgid"]/ul/li[1]/a/img/text()')
# for img in imgs:
#
# print img
# for img in imgs :
print paths
main()
解决方案
在写爬虫的时候,使用xpath一定要确认一下网页的源代码中是否有数据,如果没有,说明是异步加载的
1. 浏览器输入这个连接即可看源代码,ctrl+f 查找imgid所在的位置
view-source:https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=%E6%9A%B4%E8%B5%B0%E6%BC%AB%E7%94%BB&pn=0
2. 发现
并没有找到下面的图片列表,我们可以判定图片是js加载的
3. 寻找
F12看network(刷新才能看到),并没有发现异步请求加载的图片信息,于是我猜测数据应该就在html里,不过是放在js里,在加载图片的时候处理了
同样是上面的查看源代码的方式,查找objURL这个参数发现了真实的url
//很多,集中在html下半部分
http://img3.duitang.com/uploads/item/201608/06/20160806110540_MAcru.jpeg
解决
剩下的就交给你啦~去想办法解析出下面部分的真实url吧!
这篇关于python - 我写的Xpath 为什么爬取不到内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文