我嘗試編寫一個腳本來抓取我的網站。
但我堅持在「if語句」的第15行;它沒有進行比較。
我認爲這是一個編碼問題,或者包含其他字符。我猜。
文檔編碼爲ANSI,網站爲ISO-8859-15。如果語句在Python中不起作用
HParser.py:
from HTMLParser import HTMLParser
from htmlentitydefs import name2codepoint
import urllib2
url = 'http://DOMAIN.TLD'
req = urllib2.Request(url)
response = urllib2.urlopen(req)
the_page = response.read()
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
tag = unicode(tag)
tag = tag.strip()
print "'",tag,"'"
if tag == 'a':
for attr in attrs:
if 'src' == attr[0]:
print 'Link: ', attr[1]
def handle_endtag(self, tag):
pass
def handle_data(self, data):
pass
def handle_comment(self, data):
pass
def handle_entityref(self, name):
pass
def handle_charref(self, name):
pass
def handle_decl(self, data):
pass
parser = MyHTMLParser()
parser.feed(the_page)
是否有助於將打印語句更改爲:print'tag:',repr(tag) – 2012-05-30 18:19:10
print「'」,tag,「'」打印出來的內容是什麼?那麼print print =='a'呢? – benuuu
你的'attrs'看起來像什麼?如果'attrs'是一個字符串列表,那麼'attr [0]'將永遠是第一個字母(所以它永遠不會是整個單詞「src'')。但是如果沒有看到你是如何得到這個診斷的,就很難說更多。 –