繁体   English   中英

scrapy选择器xpath提取匹配的正则表达式或切片字符串

[英]scrapy selector xpath extract matching regex or slicing string

我是一名新手,对Python很感兴趣。

我想检索item ['rating']。 评级采用字符串形式“评级为4”,但我只需要数字...我如何获得它?

我在下面的解决方案中强调这些,但是不知道它们是否有意义。 而且没有任何工作。

> item_pub['rating'] = review.xpath('/html/body//*/div[@class="details"]/table[@class="detailtoptable"]/tbody/tr[1]/td/img/@alt').re(r'\d+') #to extract only the number since the result with extract() would be "rating is 4"

要么

 > item_pub['rating'] = review.xpath('/html/body//*/div[@class="details"]/table[@class="detailtoptable"]/tbody/tr[1]/td/img/@alt')[-1:].extract() #to extract only the number since the result with extract() would be "rating is 4"

非常感谢您的帮助,对不起我的英语,希望我的问题很清楚。

使用正则表达式是可以的。 您的Xpath不好。
这里有一些提示:

  • 无需/html/body// ,您只需//
  • 无需选择所有带有//*元素,而只需要稍后选择单个元素即可。 您可以继续并选择所需的元素: //div
  • 如果您是使用浏览器找到此xpath的,则很可能实际上没有tbody元素,因为浏览器经常添加

像这样尝试:

item_pub['rating'] = review.xpath('//div[@class="details"]/table[@class="detailtoptable"]/tr[1]/td/img/@alt').re_first(r'\d+')

通过美丽的汤,你可以这样做,

>>> from bs4 import BeautifulSoup
>>> s = '''<td> <img alt="rating is 4" title="rating is 4" src="/Shared\images\ratingstars_web8.gif"/> </td>'''
>>> [re.search(r'\d+', i['alt']).group() for i in soup.select('td > img[alt*="rating"]')]
['4']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM