【问题标题】:Python Beautifulsoup parse htmlPython Beautifulsoup 解析 html
【发布时间】:2018-07-10 18:40:24
【问题描述】:

我正在尝试使用 BeautifulSoup4 解析 html:

<tr  class="odd" >
<td><a href="show_result.php?id=7084083" title="Show the User ID DB records for the id '7084083'"  tabindex="5" >7084083</A></td>
<td><a href="show_result.php?name=bernd" title="Show the User ID DB records the name 'bernd'"   >bernd</A></td>
<td><a href="show_result.php?range=DDF+User" title="range_link"   >DDF User</A></td>
<td>mandatory</td>
<td>Solaris</td>
<td>valid</td>
<!-- xxxx old style  -->
<!-- xxxx showdetail navlink -->
<td><a class="navlink" href="show_detail.php?rec_id=283330130"  title="show the detail for this entry [alt-E]" accesskey="E"><img src="detail.gif" alt="show the detail for this entry [alt-E]" title="show the detail for this entry [alt-E]" border="0">&nbsp;</a></td>
</tr>

我想过滤掉第一个 "id=7084083" => (7084083)

【问题讨论】:

  • 到目前为止你尝试过什么?
  • 请不要在评论区放任何代码,更新你的帖子并把它放在那里,确保也编辑格式
  • soup.select_one('a[tabindex]').text

标签: python beautifulsoup html-parsing


【解决方案1】:

由于您正在搜索 html 的某个特定部分,因此使用re 而不是bs4 可能更容易:

import re
s = """
<tr  class="odd" >
<td><a href="show_result.php?id=7084083" title="Show the User ID DB records for the id '7084083'"  tabindex="5" >7084083</A></td>
<td><a href="show_result.php?name=bernd" title="Show the User ID DB records the name 'bernd'"   >bernd</A></td>
<td><a href="show_result.php?range=DDF+User" title="range_link"   >DDF User</A></td>
<td>mandatory</td>
<td>Solaris</td>
<td>valid</td>
<!-- xxxx old style  -->
<!-- xxxx showdetail navlink -->
<td><a class="navlink" href="show_detail.php?rec_id=283330130"  title="show the detail for this entry [alt-E]" accesskey="E"><img src="detail.gif" alt="show the detail for this entry [alt-E]" title="show the detail for this entry [alt-E]" border="0">&nbsp;</a></td>
</tr>
"""
final_id = re.findall('(?<=id\=)\d+', s)[0]

输出:

'7084083'

【讨论】:

    猜你喜欢
    • 2020-02-06
    • 2014-03-06
    • 2011-07-21
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多