python - 类型错误 : 'str' object is not callable

标签 python beautifulsoup

我在程序中添加了几行代码,以使用 BeautifulSoup 将 html 转换为 json,但添加的代码行出现错误。

import httplib, urllib
from bs4 import BeautifulSoup
import json

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()
htmldata = [[cell.text for cell in row("td")]for row in BeautifulSoup((data)("tr"),"lxml")]
x = json.dumps(dict(htmldata))
print x

我收到错误为

Traceback (most recent call last):
  File "commodity.py", line 12, in <module>
    data1 = [[cell.text for cell in row("td")]for row in BeautifulSoup((data)("tr"),"lxml")]
TypeError: 'str' object is not callable`enter code here`

运行代码。谁能告诉我解决此错误的正确方法。

最佳答案

您正在尝试在此处“调用”字符串:

BeautifulSoup((data)("tr"),"lxml")

(data)是一个字符串,并且 (data)("tr")是对字符串的调用。

也许您想查找所有<tr>元素:

BeautifulSoup(data, "lxml").find_all("tr")

做出完整的声明:

htmldata = [[cell.text for cell in row("td")] for row in BeautifulSoup(data, "lxml").find_all("tr")]

关于python - 类型错误 : 'str' object is not callable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32795749/

相关文章:

python - BeautifulSoup:根据前面标签的内容打印 div

python - os.mknod() 在 MacOS 上失败?

python - 附加到列表字典会增加每个键的值

python - python lxml 中的 XQuery 绝对路径

python - 在 Ubuntu 中为 Python 3.1.2 安装 Pygame

python - 加载巨大的 XML 文件并处理 MemoryError

javascript - 使用 Selenium 和 BeautifulSoup 抓取网站

python - 为什么不立即更新 Frame 的自然高度?

python - Python 中的 BeautifulSoup - 获取类型的第 n 个标签

python - 美丽汤用户警告: No parser was explicitly specified