我正在尝试从以下短语中提取国家(此处为印度尼西亚):
<small class="text-muted">
<span class="hidden-xs">Football / </span>Indonesia /
<span class="hidden-xs xh-highlight">Kick off: </span>11 Sep 2019, 11:30 </small>
此刻,我仅使用以下命令提取文本:
.xpath('.//small[@class="text-muted"]/text()').extract()
仅提取印度尼西亚的正确正则表达式命令是什么?
答案 0 :(得分:0)
也许,如果可以,我们可以从bs4
导入BeautifulSoup
中提取国家/地区:
from bs4 import BeautifulSoup
import re
string="""
<small class="text-muted">
<span class="hidden-xs">Football / </span>Indonesia /
<span class="hidden-xs xh-highlight">Kick off: </span>11 Sep 2019, 11:30 </small>
A
"""
soup = BeautifulSoup(string, 'html.parser').find_all('small')[0].text
print(re.findall(r'[^/]+/\s*([^/]+?)\s*/', soup)[0])
Indonesia
答案 1 :(得分:0)
您可以使用以下XPath-1.0表达式:
//small[@class="text-muted"]/span[@class="hidden-xs"]/following-sibling::text()
其结果为Indonesia /
。
如果要摆脱斜线,则有以下几种可能性:
从表达式中删除所有斜杠:
normalize-space(translate(//small[@class="text-muted"]/span[@class="hidden-xs"]/following-sibling::text(),"/",""))
使用substring-before()
来获取斜杠前的字符串:
normalize-space(substring-before(//small[@class="text-muted"]/span[@class="hidden-xs"]/following-sibling::text(),"/"))
使用substring-before()
获取第一个空格之前的字符串:
normalize-space(substring-before(//small[@class="text-muted"]/span[@class="hidden-xs"]/following-sibling::text()," "))
还有其他XPath表达式也可以使用。选择最适合您情况的一种。仅当您指定到当前节点的相对路径时,//
之前的前导点才是必需的。在上面的表达式中,我确实假定查找是全局的。
当然,这些XPath表达式必须被包围
.xpath('...').extract()
答案 2 :(得分:0)
问题是,您对输入了解多少?您显然不知道它包含“印度尼西亚”,但是输入的所有其他部分是否完全固定?例如,您要查找的文本是否总是总是紧跟在内容为Football /
的span元素之后?
如果是这种情况,那么您可以
//small[@class="text-muted"]/span[. = Football / ']/following-sibling::text()[1]