所以我是 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 的方式来获取这些数据,因为我不确定下一步该怎么做。
最佳答案
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','-']
希望这就是你要找的
关于python - 用漂亮的汤和 python 3.x 刮表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45521501/