【问题标题】:Python: Accessing a new <tr> while inside a different <tr> with BeautifulSoup4Python:使用 BeautifulSoup4 在不同的 <tr> 中访问新的 <tr>
【发布时间】:2020-10-09 03:45:25
【问题描述】:

我正在尝试通过使用 BeautifulSoup4 抓取本地 HTML 文件来收集一些数据。问题是,我试图获取的信息位于具有相同类标签的不同行上。我不确定如何访问它们。以下 html 屏幕截图包含我正在访问的两行,其中突出显示了我需要的数据(敏感信息被潦草写出)。

我目前的代码是:

def find_data(fileName):
    with open(fileName) as html_file:
         soup = bs(html_file, "lxml")
    hline1 = soup.find("td", class_="headerTableEntry")
    hline2 = hline1.find_next_sibling("td")
    hline3 = hline2.find_next_sibling("td")
    hline4 = hline3.find_next_sibling("td", class_="headerTableEntry")

    line1 = hline1.text
    line2 = hline2.text
    line3 = hline3.text
    #Nothing yet for lines 4,5,6

前 3 行效果很好,并给出了应有的 13、39 和 33.3%。但是对于第 4 行(应该是第二个标签和第一个标签,class=headerTableEntry),我得到一个错误“'NoneType' object is not callable”。

我的问题是,是否有不同的方法可以访问所有 6 个数据单元格,或者有没有办法编辑我编写第 4 行的工作方式?感谢您的帮助,非常感谢!

【问题讨论】:

  • 请用实际的 html 编辑您的问题,而不是图像。

标签: python html python-3.x beautifulsoup typeerror


【解决方案1】:

&lt;tr&gt; 标记不在另一个 &lt;tr&gt; 标记内,因为您可以看到第一个 &lt;tr&gt; 标记以 &lt;/tr&gt; 关闭,因此下一个 &lt;td&gt; 不是前一个的兄弟,因此它返回没有。它在下一个 &lt;tr&gt; 标记内。

Pandas 是一个很棒的包来解析 html &lt;table&gt; 标签(就是这样)。它实际上在引擎盖下使用了beautifulsoup。只需获取完整的表格,然后将表格分割为您想要的列:

html_file = '''<table>
<tr>
<td class="headerName">File:</td>
<td class="HeaderValue">Some Value</td>
<td></td>
<td class="headerName">Lines:</td>
<td class="headerTableEntry">13</td>
<td class="headerTableEntry">39</td>
<td class="headerTableEntry" style="back-ground-color:LightPink">33.3 %</td>
</tr>
<tr>
<td class="headerName">Date:</td>
<td class="HeaderValue">2020-06-18 11:15:19</td>
<td></td>
<td class="headerName">Branches:</td>
<td class="headerTableEntry">10</td>
<td class="headerTableEntry">12</td>
<td class="headerTableEntry" style="back-ground-color:#FFFF55">83.3 %</td>
</tr>
</table>'''



import pandas as pd

df = pd.read_html(html_file)[0]
df = df.iloc[:,3:]

所以对于您的代码:

def find_data(fileName):
    with open(fileName) as html_file:
        df = pd.read_html(html_file)[0].iloc[:,3:]
        print (df)

输出:

print (df)
           3   4   5       6
0     Lines:  13  39  33.3 %
1  Branches:  10  12  83.3 %

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多