python - 我写的Xpath 为什么爬取不到内容
阿神
阿神 2017-04-18 10:30:15
0
1
775

-- 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()

阿神
阿神

闭关修行中......

全部回复(1)
Peter_Zhu

在写爬虫的时候,使用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吧!

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!