1
爲什麼這段代碼不起作用並給AttributeError?Python。 AttributeError:'NoneType'對象沒有屬性'startswith'
internship = parser.find_all('a', attrs = {'title': lambda job: job.startswith('Internship')})
,而這一個工程:
internship = parser.find_all('a', attrs = {'title': lambda job: job and job.startswith('Internship')})
這是我從第一個代碼得到的錯誤:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\bs4\element.py", line 1299, in find_all
return self._find_all(name, attrs, text, limit, generator, **kwargs)
File "C:\Python27\lib\site-packages\bs4\element.py", line 549, in _find_all
found = strainer.search(i)
File "C:\Python27\lib\site-packages\bs4\element.py", line 1690, in search
found = self.search_tag(markup)
File "C:\Python27\lib\site-packages\bs4\element.py", line 1662, in search_tag
if not self._matches(attr_value, match_against):
File "C:\Python27\lib\site-packages\bs4\element.py", line 1722, in _matches
return match_against(markup)
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'startswith'
PEP008說,要'None'比較應該寫成'如果foo是None',而不是'如果FOO '。我意識到OP的代碼在這個意義上也是'不正確的',但是如果提出建議,最好推薦'合規'代碼。恕我直言。 – SiHa
SiHa,我試圖解釋OP的「和」在做什麼,因爲他顯然不明白這一點:這是他的問題的關鍵。你當然是對的,但改變比較會混淆解釋。 – BoarGules
感謝您的解釋,順便說一句,有沒有其他替代的代碼,你推薦有相同的目的呢? – garjted