2017-05-02 25 views
-1

我試圖在網站上刮掉特定表格的特定部分。Python:爲特定內容刮表

URL = https://h10145.www1.hpe.com/downloads/SoftwareReleases.aspx?ProductNumber=J9775A 

在網站上,還有就是我想從,這我能做到,但是,我得到了很多的表我不需要的其他物品的刮的HTML表格。如果您查看URL,表格由多個下拉列表組成,我只需要「當前版本」列表。

檢查元素給了我這個與Screenshot

工作,正如你所看到的,也有一些與類型「Current_Releases」表中的行,但我無法弄清楚如何拉-just-那些。

我使用Python 3.2和BeautifulSoup,以及課程

這裏的請求和CSV是我的代碼:

url = "https://h10145.www1.hpe.com/downloads/SoftwareReleases.aspx?ProductNumber=J9775A" 
r = requests.get(url) 
soup = BeautifulSoup(r.content) 
table = soup.find('table', attrs={"class": "hpui-standardHrGrid-table"}) 
headers = [header.text for header in table.find_all('th')] 
rows = [] 

for row in table.find_all('tr'): 
    rows.append([val.text.encode('utf8') for val in row.find_all('td')]) 
with open('c:\source\output_file.csv', 'w') as f: 
    writer = csv.writer(f) 
    writer.writerow(headers) 
    writer.writerows(row for row in rows if row) 

感謝您的任何建議和幫助,因爲我是新手,當它涉及到Python

回答

0

更換table.find_all('tr')table.find_all('tr', {'releasetype': 'Current_Releases')會發現<tr>與屬性releasetypeCurrent_Releases

結帳docs欲瞭解更多信息。

更新:添加完整的代碼

import csv 
import requests 
from bs4 import BeautifulSoup 

url = "https://h10145.www1.hpe.com/downloads/SoftwareReleases.aspx?ProductNumber=J9775A" 
r = requests.get(url) 
soup = BeautifulSoup(r.content, 'lxml') 
table = soup.find('table', attrs={"class": "hpui-standardHrGrid-table"}) 
headers = [header.text for header in table.find_all('th')] 
rows = [] 

for row in table.find_all('tr', {'releasetype': 'Current_Releases'}): 
    item = [] 
    for val in row.find_all('td'): 
     item.append(val.text.encode('utf8').strip()) 
    rows.append(item) 

with open('output_file.csv', 'w') as f: 
    writer = csv.writer(f) 
    writer.writerow(headers) 
    writer.writerows(rows) 

給我一個CSV與輸出

Version,Build Date,Posted Date,Notes,Size,Select 
YA.16.03.0004,17-Apr-2017,24-Apr-2017,Release notes,13.5 MB,» 
YA.16.02.0018,30-Mar-2017,06-Apr-2017,Release notes,12.7 MB,» 
YA.16.01.0012,26-Jan-2017,01-Feb-2017,Release notes,12.5 MB,» 
YA.15.18.0013,01-Sep-2016,22-Sep-2016,Release notes,11.9 MB,» 
YA.15.16.0019m (Maintenance),27-Mar-2017,29-Mar-2017,Release notes,10.2 MB,» 
+0

file這並沒有爲我工作:( –

+0

@KevinJohnson更新我的回答與預期輸出和完整代碼。 –

+0

非常感謝。<3非常感謝。看起來你包含了一個xml解析器並且改變了一些東西。這正是我需要的。 –