python - 这个字段的src属性如何用xpath选择?
PHPz
PHPz 2017-04-17 17:41:53
0
5
628
<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属性无法获取?

PHPz
PHPz

学习是最好的投资!

Antworte allen(5)
迷茫

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

大家讲道理

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

PHPzhong

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

黄舟

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

img_tag = soup.find('img', attrs=dict(class="js-refreshCaptcha captcha") )
img_tag_src = img_tag['src']
大家讲道理
captchaUrl = ''.join(response.xpath("//img[@class='js-refreshCaptcha captcha']/@src").extract())
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage