这是代码和示例结果,我只希望表格的第一列忽略其余部分。 Stackoverflow 上有类似的问题,但没有帮助。
<tr>
<td>JOHNSON</td>
<td> 2,014,470 </td>
<td>0.81</td>
<td>2</td>
</tr>
我只想要 JOHNSON,因为他是第一个 child 。 我的 python 代码是:
import requests
from bs4 import BeautifulSoup
def find_raw():
url = 'http://names.mongabay.com/most_common_surnames.htm'
r = requests.get(url)
html = r.content
soup = BeautifulSoup(html)
for n in soup.find_all('tr'):
print n.text
find_raw()
我得到的:
SMITH 2,501,922 1.0061
JOHNSON 2,014,470 0.812
最佳答案
你可以用find_all
找到所有的tr
标签,然后对于每个tr
你find
(只给出第一个)td
。如果存在,则打印它:
for tr in soup.find_all('tr'):
td = tr.find('td')
if td:
print td
关于python - 如何从 BeautifulSoup ( Python ) 中的表中获取第一个子表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31554704/