Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

我写的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()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...