我知道这不是很漂亮的代码,而且我确信有更简单的方法,但我更关心的是为什么 python 没有剥离我请求的字符。
import urllib, sgmllib
zip_code = raw_input('Give me a zip code> ')
url = 'http://www.uszip.com/zip/' + zip_code
print url
conn = urllib.urlopen('http://www.uszip.com/zip/' + zip_code)
i = 0
while i < 1000:
for line in conn.fp:
if i == 1:
print line[7:-10]
i += 1
elif i == 344:
line1 = line.strip()
line2 = line1.strip('<td>') #its not stripping the characters
print line2[17:-60]
i += 1
else:
i += 1
请您参考如下方法:
按照您的调用方式,它应该删除任何出现的 < , > , t , 和 d字符,和 only at the beginning or end of the string :
>>> '<p>some test</p>'.strip('<td>')
'p>some test</p'
如果你想删除所有出现的子字符串 <td> , 使用 replace :
>>> '<td>some test</td>'.replace('<td>', '')
'some test</td>'
请注意,如果您想将它用于某种输入清理,它很容易被规避:
>>> '<td<td>>some test</td>'.replace('<td>', '')
'<td>some test</td>'
这只是人们在尝试编写自己的 HTML 解析代码时通常会被搞砸的众多方式之一,所以也许您更愿意使用像 BeautifulSoup 这样的 HTML 解析库。或类似 lxml 的 XML 解析器.
