【问题标题】:Scraping tables with beautiful soup and python 3.x用漂亮的汤和 python 3.x 刮桌子
【发布时间】:2018-01-13 06:14:23
【问题描述】:

所以我对 python 非常陌生,并且仍在努力了解一切是如何工作的,现在我正在使用漂亮的汤来抓取表格以获取数据。我可以使用漂亮的汤导航到我想要的特定表格,但是提取实际数据让我感到难过,我尝试的一切都失败了。

这是我当前的代码:

sauce = requests.get('https://www.investsmart.com.au/managed-funds/fund/cromwell-phoenix-opportunities-fund/40665')
soup = BeautifulSoup(sauce.text, 'html.parser')
tables = soup.findChildren('table')
my_table = tables[1]
rows = my_table.findChildren(['tr'])

for tds in rows[1]:
    print(tds)

这留给我输出

 <td class="text-left">Total return</td>


<td>-2.79</td>


<td>-2.61</td>


<td>11.22</td>


<td>24.6</td>


<td>19.18</td>


<td>18.65</td>


<td>21.44</td>


<td>-</td>

我想要的只是 td 标记内的实际数字,最终我想将其分类为各自的月份并将其输出到 excel 文件中。

但是当我尝试时,我不确定如何只获取没有标签的退货:

for tds in rows[1]:
    print(tds.text)

我得到这个错误:AttributeError: 'NavigableString' object has no attribute 'text'

那么我该如何获取这些数据,以便我可以对其来源的月份进行分类并输出到 Excel,因为我不确定下一步该做什么。

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:
    sauce = requests.get('https://www.investsmart.com.au/managed-funds/fund/cromwell-phoenix-opportunities-fund/40665')
    soup = bs4.BeautifulSoup(sauce.text, 'html.parser')
    #this gets all the tables in the page, we need the second table
    table = soup.findAll('table')[1]
    #gets all the rows in that table
    rows = table.findAll('tr')
    #since the first row contains all column titles
    column_heads = [i.text.encode('utf-8') for i in rows[0].findAll('th')[1:]]
    #r will hold all the rows in the form of lists
    r = []
    for i in rows[1:]:
        r.append([k.text.encode('utf-8') for k in i.findAll('td') ])
    

    您需要做的就是使用浏览器的查看源代码工具仔细检查 html 页面,这将使您了解可以定位所需标签的结构

    输出供您参考:

    column_heads = ['1 Month %','3 Month %','6 Month %','1 Year % p.a.','2 Year % p.a.','3 Year % p.a.','5 Year % p.a.','10 Year % p.a.']
    

    encode() 函数将所有 unicode 格式的文本例如:u'Hello' 转换为字符串

    打印第一个 r 列表

    r[0] = ['Total return','-2.79','-2.61','11.22','24.6','19.18','18.65','21.44','-']
    

    我希望这就是你要找的东西

    【讨论】:

    • 谢谢,我很感激这一点,我发现了 .string 参数并让它以这种方式工作,但这似乎是一种更好的做事方式,所以我会尝试一下,看看我能做什么。作为编程新手(就像我上周开始的那样),这真的很有帮助。
    【解决方案2】:

    没有beautifulsoup,我有一个窍门。安装pandas。然后在

    之后
    import pandas as pd
    tables = pd.read_html("http:...")
    

    , tables 现在是页面上的表格列表。

    【讨论】:

    • 感谢您的建议,我其实很想学习 pandas,但我决定先学习 bs4,以尝试更多地了解 python,因为我是新手。但是在我对 bs4 感到满意之后,我会尝试这种方法。
    【解决方案3】:

    如果你想导出到 excel,我猜 csv 会起作用:

    import requests
    from bs4 import BeautifulSoup 
    
    sauce = requests.get('https://www.investsmart.com.au/managed-funds/fund/cromwell-phoenix-opportunities-fund/40665')
    soup = BeautifulSoup(sauce.text, 'html.parser')
    tables = soup.find_all('table')
    with open('csvfile.csv','w') as csv:
        for row in tables[1].find_all('tr'):
            line = ""
            for td in row.find_all(['td', 'th']):
                line += '"' + td.text + '",'
            csv.write(line + '\n')
    

    【讨论】:

      猜你喜欢
      • 2017-12-23
      • 2013-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多