2016-03-02 61 views

回答

2

由於這是BeautifulSoup具體問題,下面是一個工作BeautifulSoup的具體解決方案。這個想法是要找到具有元件的SKU#文字和locate the first table parent

import requests 
from bs4 import BeautifulSoup 


data = requests.get('http://epi.hbsna.com/products/dept.asp?msi=0&sid=6076533CE8C648AE9883BDDBED795B29&dept_id=315&parent_id=0').content 
soup = BeautifulSoup(data, "html.parser") 

table = soup.find(text="SKU#").find_parent("table") 
for row in table.find_all("tr")[1:]: 
    print([cell.get_text(strip=True) for cell in row.find_all("td")]) 

打印表的內容:

['40010001', 'ABA Service Kit', '-', '1-1/4" 10', 'None', '5-1/2"', '0.63', 'Clamp', '42710566'] 
['40010002', 'ABA Service Kit', '-', '1-1/4" 10', '5/8" RH', '5-1/2"', '0.63', 'Clamp', '42710566'] 
... 
['40010649', 'ABA Service Kit', '-', '1 1/2 - 10', '1.5', '6"', '0.50', 'Strap', '427-10517'] 
['40050604', 'ABA Service Kit', 'none', '1 1/2" - 10"', '1 1/2" LH', '6"', '0.50', 'Strap', '427-10601'] 
+0

謝謝 - 看起來很完美 - 這個代碼工作3.5 - 我得到一些錯誤 – PatrickP76

+0

@ PatrickP76是的,在3.5測試。你會得到什麼錯誤?謝謝。 – alecxe

+0

別擔心 - 我能弄明白 - 你是最好的 - 我只需要將請求更改爲3.5版本 – PatrickP76

2

如何你覺得用這個xpath體現在哪裏?

//*[./text()="SKU#"]/ancestor::table[1] 

這意味着,「找到文本確切地說是SKU#第一個元素,然後選擇其最接近的表的祖先。」

您可以在瀏覽器檢查器中通過將表達式作爲字符串傳遞給$x函數來嘗試。


beautifulsoupxpath工作見this answer

+0

如果有那個SKU#將在其他地方出現在文檔中,可以將風險選擇任何其他只會出現在表格中的文本。 – allonhadaya

+0

我是新來的,沒有嘗試甚至沒有聽說過xpath - 我會研究並希望這樣做。謝謝。 – PatrickP76

+0

@ alecxe的答案非常適合只使用'beautifulsoup',並且它讀得非常清楚! 'xpath'是一種用於導航具有大多數編程語言實現的xml文檔的語言。這是值得檢查作爲您的網頁抓取工具包的一部分。 :) – allonhadaya