Heim  >  Fragen und Antworten  >  Hauptteil

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

阿神阿神2741 Tage vor768

Antworte allen(1)Ich werde antworten

  • 天蓬老师

    天蓬老师2017-04-18 10:32:15

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

    Antwort
    0
  • StornierenAntwort