【问题标题】:Python, BeautifulSoup parsing tablePython、BeautifulSoup 解析表
【发布时间】:2017-09-12 16:00:31
【问题描述】:

我正在解析表格中的一些段落。

这是内容和代码。

txt = '''
<head><META http-equiv="Content-Type" content="text/html; charset=UTF-8">    </head><table><tr><th filter=all>Employee Name</th><th filter=all>Project     Name</th><th filter=all>Area</th><th filter=all>Date</th><th filter=all>Employee     Manager</th></tr>
<tr><td style="vnd.ms-excel.numberformat:@">David</td><td style="vnd.ms-    excel.numberformat:@">Review-2016</td><td style="vnd.ms-    excel.numberformat:@">US</td><td align=right>17/03/2016</td><td style="vnd.ms-    excel.numberformat:@">Andrew</td></tr>
<tr><td style="vnd.ms-excel.numberformat:@">Kate</td><td style="vnd.ms-excel.numberformat:@">Review 2016</td><td style="vnd.ms-excel.numberformat:@">UK</td><td align=right>21/03/2016</td><td style="vnd.ms-excel.numberformat:@">Liz</td></tr>

'''

soup = BeautifulSoup(txt, "lxml")
soup.prettify()

list_5 = soup.find_all('table')[0].find_all("tr")

for row in list_5:
    for nn in row.find_all("td"):
        print nn.text

到目前为止,文本已经得到但都放在一起,即:

David
Review-2016
US
17/03/2016
Andrew
Kate
Review 2016
UK
21/03/2016
Liz 

需要的是列形式,例如 David、Kate 或 US、UK 等。

你能帮我正确的方法吗?谢谢。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    如果你想打印David, Kate,下面的代码可以工作:

     for row in list_5[1:]:
          print(row.find_all('td')[0].text)
     #change find_all('td')[0] to find_all('td')[2] will print US UK
    

    【讨论】:

    • 你能帮我解决我的类似问题吗?这里:stackoverflow.com/questions/43033378/…
    • 解决方案是部分提供的,因为我能够获得部分和其他部分,即将输出解析为数据框是我的一大挑战。
    • 我稍后再试试!
    • @nick,顺便说一句。你能告诉我在表格中有多少列的方法吗?即 print(row.find_all('td')[X].text) - 我怎么知道 X 值?谢谢。
    • &lt;tr&gt;&lt;td style="vnd.ms-excel.numberformat:@"&gt;David...&lt;/tr&gt; ,&lt;td style="vnd.ms-excel.numberformat:@"&gt;David&lt;/td&gt;是第一个子元素,所以它在row.find_all('td')的数组中的索引号是0td 包含US 是第三个子元素,所以它的索引号是2
    猜你喜欢
    • 2014-06-16
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    相关资源
    最近更新 更多