如何从包含在 python 中解析的嵌套标签的 th 标签获取值?
how to get a value from a th tag containing a nested tag parsing in python?
如何在没有来自标签 a 的值的情况下从 th 获取值
<th scope="col">1926
<sup id="cite_ref-2011CH_22-0" class="reference">
<a href="#cite_note-2011CH-22">[22]</a>
</sup>
</th>
我试过了
table = soup.find('table', {"class": "standard"})
data_th = table.find('tbody').find_all('tr', {"class": "bright"})
for tr in data_th:
th_list = tr.find_all('th')
for th in th_list:
if(th.find('a')):
print(th.text)
但最后结果
1926[22]
1931[23]
1939[23]
我需要
1926
1931
1939
一种方法是 select 只有目标文本。
th.find(text=True, recursive=False)
示例
from bs4 import BeautifulSoup
html='''
<th scope="col">1926
<sup id="cite_ref-2011CH_22-0" class="reference">
<a href="#cite_note-2011CH-22">[22]</a>
</sup>
another text
</th>
'''
soup = BeautifulSoup(html)
for th in soup.find_all('th'):
print(th.find(text=True, recursive=False).text)
如何在没有来自标签 a 的值的情况下从 th 获取值
<th scope="col">1926
<sup id="cite_ref-2011CH_22-0" class="reference">
<a href="#cite_note-2011CH-22">[22]</a>
</sup>
</th>
我试过了
table = soup.find('table', {"class": "standard"})
data_th = table.find('tbody').find_all('tr', {"class": "bright"})
for tr in data_th:
th_list = tr.find_all('th')
for th in th_list:
if(th.find('a')):
print(th.text)
但最后结果
1926[22]
1931[23]
1939[23]
我需要
1926
1931
1939
一种方法是 select 只有目标文本。
th.find(text=True, recursive=False)
示例
from bs4 import BeautifulSoup
html='''
<th scope="col">1926
<sup id="cite_ref-2011CH_22-0" class="reference">
<a href="#cite_note-2011CH-22">[22]</a>
</sup>
another text
</th>
'''
soup = BeautifulSoup(html)
for th in soup.find_all('th'):
print(th.find(text=True, recursive=False).text)