【发布时间】:2020-04-30 06:23:41
【问题描述】:
我是 Beautiful Soup 的新手,我有这样的数据,其中包含 3 组用户数据(对于这种情况)。
我想获取每个 USER_ID 的所有信息并保存到数据库。
- 用户 ID
- 标题
- 内容
- PID(不是每个用户都有这一行)
- 日期
- 网址
<table align="center" border="0" style="width:550px">
<tbody>
<tr>
<td colspan="2">USER_ID 11111</td>
</tr>
<tr>
<td colspan="2">string_a</td>
</tr>
<tr>
<td colspan="2"><strong>content: aaa</strong></td>
</tr>
<tr>
<td colspan="2"><strong>date:</strong>2020-05-01 00:00:00 To 2020-05-03 23:59:59</td>
</tr>
<tr>
<td colspan="2"><strong>URL:https://aaa.com</strong></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan="2">USER_ID 22222</td>
</tr>
<tr>
<td colspan="2">string_b</td>
</tr>
<tr>
<td colspan="2"><strong>content: bbb</strong></td>
</tr>
<tr>
<td colspan="2"><strong>date:</strong>2020-05-01 00:00:00 To 2020-05-03 23:59:59</td>
</tr>
<tr>
<td colspan="2"><strong>URL:https://aaa.com</strong></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan="2">USER_ID 33333</td>
</tr>
<tr>
<td colspan="2">string_c</td>
</tr>
<tr>
<td colspan="2"><strong>content: ccc</strong></td>
</tr>
<tr>
<td colspan="2"><strong>date:</strong>2020-05-01 00:00:00 To 2020-05-03 23:59:59</td>
</tr>
<tr>
<td colspan="2"><strong>PID:</strong><strong>ABCDE</strong></td>
</tr>
<tr>
<td colspan="2"><strong>URL:https://ccc.com</strong></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
</tbody>
</table>
我的问题是,
所有数据仅在 td 内,不包含 div 名称和父标签。我无法分成 3 组数据。
我尝试了下面的代码,它可以找到所有的 USER_ID,但我不知道如何获取每个 USER_ID 的其他数据
soup = BeautifulSoup(content, 'html.parser')
p = soup.find_all('td', text=re.compile("^USER_ID"))
for item in p:
title = item.find_next_siblings('td') # <--- return empty
...
我正在使用
蟒蛇 3.6
django 2.0.2
【问题讨论】:
-
检查下面的答案:)
标签: python beautifulsoup