2016-09-22 37 views
0

我試圖構建一個爬蟲,我想打印 我使用Python 3.5Python的類型錯誤回溯(最近通話最後一個)

在該網頁上的所有鏈接有我的代碼

import requests 
from bs4 import BeautifulSoup 
def crawler(link): 
    source_code = requests.get(link) 
    source_code_string = str(source_code) 
    source_code_soup = BeautifulSoup(source_code_string,'lxml') 
    for item in source_code_soup.findAll("a"): 
     title = item.string 
     print(title) 

crawler("https://www.youtube.com/watch?v=pLHejmLB16o") 

但我得到這樣

TypeError         Traceback (most recent call last) 
<ipython-input-13-9aa10c5a03ef> in <module>() 
----> 1 crawler('http://archive.is/DPG9M') 

TypeError: 'module' object is not callable 
+0

收到這個錯誤你嘗試過重命名你的'crawler'方法? –

+0

是的,我把「crawler」改成了「cat」,但是還是一樣的錯誤 – Travis

回答

2

如果意圖是隻打印鏈接的標題,你是一個小失誤的錯誤,更換線路:

source_code_string = str(source_code) 

使用

source_code_string = source_code.text 

除此之外代碼看起來罰款和運行。 讓我們稱之爲web_crawler_v1.py

import requests 
from bs4 import BeautifulSoup 
def crawler(link): 
    source_code = requests.get(link) 
    source_code_string = source_code.text 
    source_code_soup = BeautifulSoup(source_code_string,'lxml') 
    for item in source_code_soup.findAll("a"): 
     title = item.string 
     print(title) 


crawler("https://www.youtube.com/watch?v=pLHejmLB16o") 

文件以及有關錯誤,你不應該,如果你正確地調用文件這樣

python3 wen_crawler_v1.py 
+0

謝謝它的作品! – Travis

+0

我還有一個問題。我正在使用Jupyter筆記本,並且當我在筆記本RootPython中鍵入這些代碼時,它就可以工作。但是當我創建一個新的py文件(test.py)並在其中放入相同的代碼並鍵入「import test.py」時,它不起作用,你知道爲什麼嗎? – Travis

+0

我已經測試過它,它可以正常工作,但它是否在您從中調用它的同一位置?因爲如果不是,那可能會成爲問題。 –

相關問題