您的位置:首页技术文章
文章详情页

python - 我写的Xpath 为什么爬取不到内容

浏览:63日期:2022-08-13 13:30:26

问题描述

-- coding:utf-8 --

import lxml,requests,sysfrom bs4 import BeautifulSoupfrom 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:

在写爬虫的时候,使用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=02. 发现

并没有找到下面的图片列表,我们可以判定图片是js加载的

3. 寻找

F12看network(刷新才能看到),并没有发现异步请求加载的图片信息,于是我猜测数据应该就在html里,不过是放在js里,在加载图片的时候处理了

同样是上面的查看源代码的方式,查找objURL这个参数发现了真实的url

//很多,集中在html下半部分http://img3.duitang.com/uploads/item/201608/06/20160806110540_MAcru.jpeg解决

剩下的就交给你啦~去想办法解析出下面部分的真实url吧!

标签: Python 编程
相关文章: