2015-09-27 106 views
0

我用我的代碼BeautifulSoup找到「TR」和「TD」的所有現象,而是在代碼中收到一個錯誤的第二次使用兩次使用BeautifulSoup當「NoneType」對象不是可調用。類型錯誤:在代碼

params = urllib.urlencode({'cmm': 'onion', 'mkt': '', 'search': ''}) 
headers = {'Cookie': 'ASPSESSIONIDCCRBQBBS=KKLPJPKCHLACHBKKJONGLPHE; ASP.NET_SessionId=kvxhkhqmjnauyz55ult4hx55; ASPSESSIONIDAASBRBAS=IEJPJLHDEKFKAMOENFOAPNIM','Origin': 'http://agmarknet.nic.in', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6','Upgrade-Insecure-Requests': '1','User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded','Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Cache-Control': 'max-age=0','Referer': 'http://agmarknet.nic.in/mark2_new.asp','Connection': 'keep-alive'} 
conn = httplib.HTTPConnection("agmarknet.nic.in") 
conn.request("POST", "/SearchCmmMkt.asp", params, headers) 
response = conn.getresponse() 
print response.status, response.reason 
data = response.read() 
soup = BeautifulSoup(data,'lxml') 
result = soup.findAll("tr") 
for y in result: 
    row = BeautifulSoup(y,'lxml') 
    k = row.findAll("td") 
    for x in k: 
     text = x.text 
     print text 

我收到下面的錯誤

Traceback (most recent call last): 
    File "commodity.py", line 15, in <module> 
    row = BeautifulSoup(y,'lxml') 
    File "/usr/local/lib/python2.7/dist-packages/bs4/__init__.py", line 175, in __init__ 
    markup = markup.read() 
TypeError: 'NoneType' object is not callable. 

誰能幫我解決這個問題,並告訴我使用它正確的方式。

+0

你爲什麼cpassing'y'到'BeautifulSoup()'*再次*?它不是一個HTML字符串,它是一個BeautifulSoup'Element'對象。 –

回答

1

首先你不應該傳遞Element對象BeautifulSoup()。只是完全消除BeautifulSoup(y, 'lxml')電話:

for row in result: 
    cells = row.findAll("td") 
    for cell in cells: 
     text = cell.text 
     print text