繁体   English   中英

使用soup.find()方法的漂亮汤拼图

[英]Beautiful Soup puzzle with soup.find() method

我正在学习Beautiful Soup和Python,在这种情况下,我正在使用包含不同年份流行的婴儿名字的html文件集(例如baby1990.html等)在Regex上进行Google教程的“婴儿名字”练习。 如果您对此感兴趣,可以找到此数据集: https : //developers.google.com/edu/python/exercises/baby-names

html文件包含一个特定的表,该表存储了常用的婴儿名字,并且其html代码如下:

<table width="100%" border="0" cellspacing="0" cellpadding="4" summary="formatting">
<tr valign="top"><td width="25%" class="greycell">
<a href="../OACT/babynames/background.html">Background information</a>
<p><br />
&nbsp; Select another <label for="yob">year of birth</label>?<br />      
<form method="post" action="/cgi-bin/popularnames.cgi">
&nbsp; <input type="text" name="year" id="yob" size="4" value="1990">
<input type="hidden" name="top" value="1000">
<input type="hidden" name="number" value="">
&nbsp; <input type="submit" value="   Go  "></form>
</td><td>
<h3 align="center">Popularity in 1990</h3>
<p align="center">
<table width="48%" border="1" bordercolor="#aaabbb"
 cellpadding="2" cellspacing="0" summary="Popularity for top 1000">
<tr align="center" valign="bottom">
<th scope="col" width="12%" bgcolor="#efefef">Rank</th>
<th scope="col" width="41%" bgcolor="#99ccff">Male name</th>
<th scope="col" bgcolor="pink" width="41%">Female name</th></tr>
<tr align="right"><td>1</td><td>Michael</td><td>Jessica</td> # Targeted row
<tr align="right"><td>2</td><td>Christopher</td><td>Ashley</td> # Targeted row
etc...

html文件中还有一个我不想捕获的表,它具有以下html代码。

  <table width="100%" border="0" cellspacing="0" cellpadding="4">
  <tbody>
  <tr><td class="sstop" valign="bottom" align="left" width="25%">
      Social Security Online
    </td><td valign="bottom" class="titletext">
      <!-- sitetitle -->Popular Baby Names
    </td>
  </tr>
  <tr bgcolor="#333366"><td colspan="2" height="2"></td></tr>
  <tr><td class="graystars" width="25%" valign="top">
       <a href="../OACT/babynames/">Popular Baby Names</a></td><td valign="top"> 
      <a href="http://www.ssa.gov/"><img src="/templateimages/tinylogo.gif"
      width="52" height="47" align="left"
      alt="SSA logo: link to Social Security home page" border="0"></a><a name="content"></a>
      <h1>Popular Names by Birth Year</h1>September 12, 2007</td>
  </tr>
  <tr bgcolor="#333366"><td colspan="2" height="1"></td></tr>
</tbody></table>

在比较两个表的表标签时,我得出结论,目标表(我要捕获的表)的独特特征是“摘要”属性,该属性似乎具有“格式”值。 因此,我尝试了以下命令:

right_table = soup.find("table", summary = "formatting")

但是,此命令无法选择目标表。 相反,以下命令成功执行:

table = soup.find(summary="Popularity for top 1000")

您能否通过查看html代码来解释为什么第一个命令失败而第二个命令成功?

您的建议将不胜感激。

在此处输入图片说明

之前我回答了您的问题,该代码有效。

还有一件事, html.patser在python2中被破坏了,不要使用它,请使用lxml

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM