2011-10-14 71 views
1

我正在製作一個小型的python腳本來自動登錄到網站。但我卡住了。打印某些HTML Python機械化

我期待打印到終端的HTML的一小部分,坐落在網站上的HTML文件這個標籤內:

<td class=h3 align='right'>&nbsp;&nbsp;John Appleseed</td><td>&nbsp;<a href="members_myaccount.php"><img border=0 src="../tbs_v7_0/images/myaccount.gif" alt="My Account"></a></td> 

但是我怎麼提取和打印只是名字,約翰·蘋果核戰記?

順便說一下,我在Mac上使用Pythons的機械化。

回答

7

機械化僅僅是用於獲取的HTML好。一旦你想從HTML中提取信息,你可以使用例如BeautifulSoup。 (見我的回答類似的問題:Web mining or scraping or crawling? What tool/library should I use?

具體情況取決於<td>位於HTML(目前還不清楚從你的問題),你可以使用下面的代碼:

html = ... # this is the html you've fetched 

from BeautifulSoup import BeautifulSoup 

soup = BeautifulSoup(html) 
# use this (gets all <td> elements) 
cols = soup.findAll('td') 
# or this (gets only <td> elements with class='h3') 
cols = soup.findAll('td', attrs={"class" : 'h3'}) 
print cols[0].renderContents() # print content of first <td> element 
+0

用於獲取html。爲什麼不使用urllib.urlopen()。就我個人而言,我從來沒有使用機械化,因爲我從來沒有覺得它的需要。 –

+1

@shadyabhi:'urllib'也不錯,但這取決於你的需求。當你必須處理代理或會話狀態,或者獲取或填寫表單時,我發現機械化很有用... – Rabarberski

1

由於您還沒有提供完整的HTML頁面,現在唯一的選擇是使用string.find()或正則表達式。

但是,找到這個的標準方法是使用xpath。看到這個問題:How to use Xpath in Python?

您可以使用firefox的「檢查元素」功能獲取元素的xpath。

例如,如果你想在stackoverflow站點找到用戶名的XPATH。

  • 打開Firefox和登錄到網站&右鍵點擊用戶名(在我的情況shadyabhi),然後選擇檢查元素。
  • 將鼠標懸停在標籤上或右鍵單擊它並「複製xpath」。

enter image description here

1

你可以用一個解析器來提取文檔中的任何信息。我建議你使用lxml模塊。

這裏有一個例子:

from lxml import etree 
from StringIO import StringIO 

parser = etree.HTMLParser() 

tree = etree.parse(StringIO("""<td class=h3 align='right'>&nbsp;&nbsp;John Appleseed</td><td>&nbsp;<a href="members_myaccount.php"><img border=0 src="../tbs_v7_0/images/myaccount.gif" alt="My Account"></a></td>"""),parser) 


>>> tree.xpath("string()").strip() 
u'John Appleseed' 

更多有關lxmlhere

+0

嗯..當名稱改變時會發生什麼?我希望能夠以任何人的身份登錄此腳本,而不僅僅是John Appleseed –

+0

您可以在該標記中添加任何想要的名稱: '>>> tree = etree.parse(StringIO(「」「    富酒吧​​  My Account 「」 「),語法分析器) >>> tree.xpath(」 串()「)。條() u'Foo Bar'' –

+0

不,名稱會根據您登錄的用戶而變化;我沒有擁有或有權訪問該網站 –