suchen

Heim  >  Fragen und Antworten  >  Hauptteil

python - 这个字段的src属性如何用xpath选择?

<img class="js-refreshCaptcha captcha" width="120" height="30" data-tip="s$t$看不清楚?换一张" alt="验证码" src="/captcha.gif?r=1462431202340&amp;type=login" style="display: block;">

这个字段的src属性如何用xpath选择?

我的写法是:

captcha_url = response.xpath('/html/body/p[1]/p/p[2]/p[2]/form/p[1]/p[3]/p/img/@src').extract()

中间的xpath是从chrome直接copy的
但是无法显示出src属性,最后弹出的是[]
不知道哪里有问题、
另外如果知道css选择器怎么写的,也可以告知一下,我看到class中有空格,不知道如何选择.
我的写法是:

captcha_url = response.css('.js-refreshCaptcha .captcha::attr(src)').extract()

从Scrapy命令行中一步步测试得到,是不是因为是JS动态生成的原因?才会导致@src属性无法获取?

PHPzPHPz2889 Tage vor631

Antworte allen(5)Ich werde antworten

  • 迷茫

    迷茫2017-04-17 17:43:53

    你想干啥,抓取到的html进行过滤吗?可以考虑正则查找

    Antwort
    0
  • 大家讲道理

    大家讲道理2017-04-17 17:43:53

    chrome有个工具叫xpath-helper,可以去应用商店下载,这样就可以用这个工具来检查你的xpath语法是否正确了。
    另外如果语法正确,但是在程序中提取不到,这时就要考虑原网页是动态页面,需要用到jsjs解析了。

    Antwort
    0
  • PHPz

    PHPz2017-04-17 17:43:53

    浏览器有容错机制,对于不规范的html标签,会进行修正,所以你在控制台看到的页面结构,和你用代码请求到的页面结构可能是不一样的。
    解决方案:
    把选择器的范围放的松一点
    使用class去定位
    在代码中打断点,单步执行去定位这个标签的xpath规则

    Antwort
    0
  • 黄舟

    黄舟2017-04-17 17:43:53

    我一般使用bs4, 无脑解决. 用正则也行,但是伤脑

    img_tag = soup.find('img', attrs=dict(class="js-refreshCaptcha captcha") )
    img_tag_src = img_tag['src']

    Antwort
    0
  • 大家讲道理

    大家讲道理2017-04-17 17:43:53

    captchaUrl = ''.join(response.xpath("//img[@class='js-refreshCaptcha captcha']/@src").extract())
    

    Antwort
    0
  • StornierenAntwort