python - 从网络数据中提取两个表的内容

标签 python web-scraping beautifulsoup

如何从此 html 数据中检索所有 td 信息:

<h1>All staff</h1>
<h2>Manager</h2>
<table class="StaffList">
    <tbody>
        <tr>
            <th>Name</th>
            <th>Post title</th>
            <th>Telephone</th>
            <th>Email</th>
        </tr>
        <tr>
            <td>
                <a href="http://profiles.strx.usc.com/Profile.aspx?Id=Jon.Staut">Jon Staut</a>
            </td>
            <td>Line Manager</td>
            <td>0160 315 3832</td>
            <td>
                <a href="mailto:Jon.staut@strx.usc.com">Jon.staut@strx.usc.com</a> &nbsp;</td>
        </tr>
    </tbody>
</table>
<h2>Junior Staff</h2>
<table class="StaffList">
    <tbody>
        <tr>
            <th>Name</th>
            <th>Post title</th>
            <th>Telephone</th>
            <th>Email</th>
        </tr>
        <tr>
            <td>
                <a href="http://profiles.strx.usc.com/Profile.aspx?Id=Peter.Boone">Peter Boone</a>
            </td>
            <td>Mailer</td>
            <td>0160 315 3834</td>
            <td>
                <a href="mailto:Peter.Boone@strx.usc.com">Peter.Boone@strx.usc.com&nbsp;</a>
            </td>
        </tr>
        <tr>
            <td>
                <a href="http://profiles.strx.usc.com/Profile.aspx?Id=John.Peters">John Peters</a>
            </td>
            <td>Builder</td>
            <td>0160 315 3837</td>
            <td>
                <a href="mailto:John.Peters@strx.usc.com">John.Peters@strx.usc.com</a>
            </td>
        </tr>
    </tbody>
</table>

这是我生成错误的代码:

response =requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.findAll('table', attrs={'class': 'StaffList'})

list_of_rows = []
for row in table.findAll('tr'): #2 rows found in table -loop through
    list_of_cells = []
    for cell in row.findAll('td'): # each cell in in a row
        text = cell.text.replace('&nbsp','')
        list_of_cells.append(text)
    #print list_of_cells
    list_of_rows.append(list_of_cells) 
#print all cells in the two rows
print list_of_rows 

错误消息:

AttributeError: 'ResultSet' object has no attribute 'findAll'

我需要做什么才能让代码输出两个web表中的所有信息?

最佳答案

问题从这一行开始:

table = soup.findAll('table', attrs={'class': 'StaffList'})

findAll 返回一个没有属性 findAll 的数组。

只需将 findAll 更改为 find: table = soup.find('table', attrs={'class': 'StaffList'})

关于python - 从网络数据中提取两个表的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36666074/

相关文章:

python - 如何处理 Beautifulsoup 递归错误(或解析错误)

python - 通过下拉菜单搜索并通过文本选择元素

web-scraping - 使用 JSoup 抓取电子邮件和链接

python - tkinter gui 编程中的 AttributeError

python - 火车出发板代码 Tkinter

c# - 如何使用 C# 调用没有名称的 Javascript

python - 使用 beautifulsoup 从表单中提取隐藏值

python - 使用 Python 抓取网页

python - 在 PyOpt 库中使用 SLSQP 求解器时出现类型错误

python - 使用 django admin 进行一对多内联选择