Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用BeautifulSoup3在div标记内的span标记中选择文本?_Python_Python 3.x_Beautifulsoup - Fatal编程技术网

Python 如何使用BeautifulSoup3在div标记内的span标记中选择文本?

Python 如何使用BeautifulSoup3在div标记内的span标记中选择文本?,python,python-3.x,beautifulsoup,Python,Python 3.x,Beautifulsoup,我有一行代码: scoreline_div = soup.find("div", { "class" : "score-line" }) 它在页面上选择一个div标记页面,如下所示: <div class="score-line"><span class="home-team team team-900">South Africa</span><span class="score">27 - 27</span><span cla

我有一行代码:

scoreline_div = soup.find("div", { "class" : "score-line" })
它在页面上选择一个div标记页面,如下所示:

<div class="score-line"><span class="home-team team team-900">South Africa</span><span class="score">27 - 27</span><span class="away-team team team-100">Australia</span></div>
南非27-27澳大利亚
如何选择第一个和第三个
span
(南非、澳大利亚)的文本?此外,span标记的类也会发生变化,因此我可以不搜索span标记的
,而选择第一个和第三个span标记来执行此操作吗

您可以使用方法获取跨度列表:

scoreline_div = soup.find("div", { "class" : "score-line" })
spans = scoreline_div.find_all('span')
# spans[0].text should return 'South Africa'
# spans[2].text should return 'Australia'
您可以使用方法获取跨距列表:

scoreline_div = soup.find("div", { "class" : "score-line" })
spans = scoreline_div.find_all('span')
# spans[0].text should return 'South Africa'
# spans[2].text should return 'Australia'
单线解决方案:

s1,s2 = soup.find("div", { "class" : "score-line" }).select('span:nth-of-type(1),span:nth-of-type(3)')
print(s1.text, s2.text)
输出:

South Africa Australia
单线解决方案:

s1,s2 = soup.find("div", { "class" : "score-line" }).select('span:nth-of-type(1),span:nth-of-type(3)')
print(s1.text, s2.text)
输出:

South Africa Australia

为什么不通过位置访问这些跨度?如何访问?您的意思是键入
分数线\u div.span[0]
?它不起作用,给我一个简单的错误,使用
nth类型
selector或者为什么不按位置访问这些跨距?如何?您的意思是键入
分数线\u div.span[0]
?它不起作用,给了我一个简单的错误与
n的类型
选择器