python - 我寫的Xpath 為什么爬取不到內容
問題描述
-- 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吧!
相關文章:
1. python3.x - python3.5使用pyinstaller打包報錯找不到libpython3.5mu.so.1.0等文件求解?2. MySQL中的enum類型有什么優點?3. flask - python web中如何共享登錄狀態?4. python3.x - python連oanda的模擬交易api獲取json問題第二問5. python - TypeError: tryMsgcode() takes exactly 2 arguments (0 given)6. mysql - 無恥的請教一條sql7. phpStudy2017輕巧版mysql無法啟動8. 為什么我寫的PHP不行9. centos7 編譯安裝 Python 3.5.1 失敗10. 為什么我輸入了refresh不會跳轉?請教大神支招!
