2009-07-20 50 views
3

我試圖做一些簡單的字符串操作與超鏈接的href屬性提取使用Beautiful Soup簡單的Python /美麗的湯類型的問題

from BeautifulSoup import BeautifulSoup 
soup = BeautifulSoup('<a href="http://www.some-site.com/">Some Hyperlink</a>') 
href = soup.find("a")["href"] 
print href 
print href[href.indexOf('/'):] 

我得到的是:

Traceback (most recent call last): 
    File "test.py", line 5, in <module> 
    print href[href.indexOf('/'):] 
AttributeError: 'unicode' object has no attribute 'indexOf' 

我應該如何將href轉換成普通字符串?

回答

8

Python字符串沒有indexOf方法。

使用href.index('/')

href.find('/')是相似的。但是如果找不到字符串,則find返回-1,而index產生ValueError

所以正確的事情是使用index(因爲'...'[ - 1]將返回字符串的最後一個字符)。

+1

也值得注意的Unicode字符串將具有所有相同的方法一個常規的字符串 – dbr 2009-07-20 12:17:21

0

href是一個unicode字符串。如果您需要常規字符串,則使用

regular_string = str(href)