简单的 Python / Beautiful Soup 问题
我正在尝试用Beautiful Soup提取的超链接的href属性进行一些简单的字符串处理:
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
转换成普通的字符串呢?
3 个回答
0
href是一个Unicode字符串。如果你需要普通字符串,可以使用
regular_string = str(href)
0
你是说 find(),而不是 indexOf()。
10
在Python中,字符串没有一个叫做 indexOf
的方法。
你可以用 href.index('/')
来找到某个字符的位置。
另外, href.find('/')
也可以做到类似的事情。不过, find
如果找不到这个字符,会返回 -1
,而 index
则会抛出一个 ValueError
错误。
所以,正确的做法是使用 index
(因为用 '...'[-1] 可以得到字符串的最后一个字符)。