Python scrapy选择器xpath提取匹配的正则表达式或切片字符串
我是scrapy的新手,对Python有点了解 我想检索项目['rating']。评级是字符串形式的“评级为4”,但我只想要数字。。。我怎样才能得到它 我在下面思考这些解决方案,但不知道它们是否有意义。没有人在工作Python scrapy选择器xpath提取匹配的正则表达式或切片字符串,python,regex,xpath,scrapy,selector,Python,Regex,Xpath,Scrapy,Selector,我是scrapy的新手,对Python有点了解 我想检索项目['rating']。评级是字符串形式的“评级为4”,但我只想要数字。。。我怎样才能得到它 我在下面思考这些解决方案,但不知道它们是否有意义。没有人在工作 > item_pub['rating'] = review.xpath('/html/body//*/div[@class="details"]/table[@class="detailtoptable"]/tbody/tr[1]/td/img/@alt').re(r'\d+'
> 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"
或
非常感谢你的帮助,我的英语很抱歉,我希望我的问题是清楚的。通过美味的汤,你可以这样做
>>> 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']
>>来自bs4导入组
>>>s=“”“
>>>[r'\d+',i['alt']].group()搜索汤中的i。选择('td>img[alt*=“rating”]')]
['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+')
发布一个示例html文件。当您期望单个值时,有
re_first
方法。
item_pub['rating'] = review.xpath('//div[@class="details"]/table[@class="detailtoptable"]/tr[1]/td/img/@alt').re_first(r'\d+')