2009-07-20 47 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)