【问题标题】:Beautiful Soup Scraping table美丽的汤刮桌
【发布时间】:2019-03-13 05:00:47
【问题描述】:

我有一小段代码可以从网站上抓取表格数据,然后以 csv 格式显示。问题是 for 循环多次打印记录。我不确定这是否是由于
标签。顺便说一句,我是 Python 新手。感谢您的帮助!

#import needed libraries
import urllib
from bs4 import BeautifulSoup
import requests
import pandas as pd
import csv
import sys
import re


# read the data from a URL
url = requests.get("https://www.top500.org/list/2018/06/")

# parse the URL using Beauriful Soup
soup = BeautifulSoup(url.content, 'html.parser')

newtxt= ""
for record in soup.find_all('tr'):
    tbltxt = ""
    for data in record.find_all('td'):
        tbltxt = tbltxt + "," + data.text
        newtxt= newtxt+ "\n" + tbltxt[1:]
        print(newtxt)

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:
    from bs4 import BeautifulSoup
    import requests
    
    url = requests.get("https://www.top500.org/list/2018/06/")
    soup = BeautifulSoup(url.content, 'html.parser')
    table = soup.find_all('table', attrs={'class':'table table-condensed table-striped'})
    for i in table:
        tr = i.find_all('tr')
        for x in tr:
            print(x.text)
    

    或者使用 pandas 解析表格的最佳方式

    import pandas as pd
    table = pd.read_html('https://www.top500.org/list/2018/06/', attrs={
        'class': 'table table-condensed table-striped'}, header = 1)
    print(table)
    

    【讨论】:

    • 喜欢熊猫解决方案:)
    【解决方案2】:

    它会多次打印大部分数据,因为您在获取每个<td></td> 的文本后打印的newtext 变量只是累积所有值。让它工作的最简单方法可能是将行 print(newtxt) 移到两个 for 循环之外 - 也就是说,让它完全不缩进。然后,您应该会看到所有文本的列表,其中每一行的文本换行,而一行中每个单独单元格的文本以逗号分隔。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-15
      • 2021-01-15
      • 2021-09-12
      • 2020-12-13
      • 2014-05-28
      • 2020-09-28
      • 2021-11-19
      相关资源
      最近更新 更多