Python-爬蟲10-找出表格內的資料

找出表格內的資料

1.抓取表格的售價

2.計算所有商品的平均價格

目標位置:http://blog.castman.net/py-scraping-analysis-book/ch2/table/table.html
 

1.抓取表格的售價

 prices = []
    #方法1
    rows = soup.find('table', 'table').tbody.find_all('tr')
    #方法2
    	rowsa = soup.find('table', 'table')
    	rowsb = rowsa.tbody.find_all('tr')
    for row in rows:
        price = row.find_all('td')[2].text
        prices.append(int(price))
        

參考

2.計算所有商品的平均價格

print(sum(prices)/len(prices))

 

完整檔:

import requests
from bs4 import BeautifulSoup
def main():
   resp = requests.get('http://blog.castman.net/py-scraping-analysis-book/ch2/table/table.html')
   soup = BeautifulSoup(resp.text, 'html.parser')
   prices = []
   rowsa = soup.find('table', 'table')
   rowsb = rowsa.tbody.find_all('tr')
 
   
   #print(rowsb);
   for row in rowsb:
       price = row.find_all('td')[2].text
       print(price)
       prices.append(int(price))
       
   print(prices)
   print(sum(prices)/len(prices))#平均
   
if __name__ == '__main__':
   main()

參考

參考:http://blog.castman.net/py-scraping-analysis-book/

Yiru@Studio - 關於我 - 意如