python - 如何在python中解析html表格

我是解析表和正则表达式的新手,你能帮忙用python解析这个吗:

<table callspacing="0" cellpadding="0">
    <tbody><tr>
    <td>1text&nbsp;2text</td>
    <td>3text&nbsp;</td>
    </tr>
    <tr>
    <td>4text&nbsp;5text</td>
    <td>6text&nbsp;</td>
    </tr>
</tbody></table>

我需要“3text”和“6text”

最佳答案

您可以使用 CSS 选择器 select()select_one() 来获取“3text”和“6text”,如下所示:

import requests
from bs4 import BeautifulSoup
html_doc='''
<table callspacing="0" cellpadding="0">
    <tbody><tr>
    <td>1text&nbsp;2text</td>
    <td>3text&nbsp;</td>
    </tr>
    <tr>
    <td>4text&nbsp;5text</td>
    <td>6text&nbsp;</td>
    </tr>
</tbody></table>
'''

soup = BeautifulSoup(html_doc, 'lxml')
soup1 = soup.select('tr')

for i in soup1:
    print(i.select_one('td:nth-child(2)').text)

你也可以使用find_all方法:

trs = soup.find('table').find_all('tr')

for i in trs:
    tds = i.find_all('td')
    print(tds[1].text)

结果:

3text 
6text 

https://stackoverflow.com/questions/63030178/

相关文章:

python - matplotlib plt.ylim 引发错误列表对象不可调用

python - 属性错误 : 'list' object has no attribute 'en

javascript - 如何为 Angular Material Slide Toggle 设置默

javascript - 在嵌套导航器中导航时未定义 route.params?

javascript - 将变量传递给自定义 Svelte Web 组件

r - 拆分字符串、标记子字符串并将标记转换为数字向量

reactjs - React Native 删除 Flatlist 中的底部空间

python - pandas Groupby 求和并连接

python - GoogleTrans Python 不翻译

reactjs - 避免在组件加载时对组件使用多个 useEffect