Python 仅从for循环返回第一个元素
我有一个url,在其中我希望在打印时获取产品名称列表我获取所有产品名称,我正在创建一个web服务,因此我必须返回产品名称,但我仅获取第一个元素,我已将产品名称移动到列表中,然后返回,但仍然收到一个错误Python 仅从for循环返回第一个元素,python,web-services,Python,Web Services,我有一个url,在其中我希望在打印时获取产品名称列表我获取所有产品名称,我正在创建一个web服务,因此我必须返回产品名称,但我仅获取第一个元素,我已将产品名称移动到列表中,然后返回,但仍然收到一个错误 AttributeError("'unicode' object has no attribute 'append'",) 这是我的密码 from bottle import route, run import urllib2 from mechanize import Browser from
AttributeError("'unicode' object has no attribute 'append'",)
这是我的密码
from bottle import route, run
import urllib2
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import sys
import csv
import re
@route('/hello')
def hello():
texts=list();
result=' ,'
mech = Browser()
url = "http://www.amazon.com"
page = mech.open(url)
html = page.read()
soup = BeautifulSoup(html)
last_page = soup.find('div', id="nav_subcats")
for elm in last_page.findAll('a'):
texts = elm.text
texts=texts.replace(",",";")
links = elm.get('href')
links=url+links
alltexts=texts+links
texts.append(alltexts)
return texts
run(host='localhost', port=8080, debug=True)
这是因为您正在尝试对unicode字符串追加(这是一种列表方法)
>>> texts = []
>>> texts.append(123)
>>> texts
[123]
>>> texts = u"Test"
>>> texts.append(" Hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'unicode' object has no attribute 'append'
>>文本=[]
>>>文本。附加(123)
>>>文本
[123]
>>>文本=u“测试”
>>>text.append(“你好”)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:“unicode”对象没有属性“append”
不确定此位:
。。。
所有文本=文本+链接
text.append(所有文本)
返回文本
除了DhruvPathak提到的附加之外,还有几个其他问题:
1) 您正在连接文本和链接并分配给所有文本,但随后您试图将其追加回文本
2) 您的返回在循环中,因此将在第一次迭代后发生这就是为什么只返回第一个元素的原因
我想你需要更像
alltexts = []
for elm in last_page.findAll('a'):
texts = elm.text
texts=texts.replace(",",";")
links = elm.get('href')
links=url+links
alltexts.append(texts+links)
return alltexts
真的不整洁的问题,就像不整洁的代码一样。好的,我已经替换了文本。附加(文本),现在我只得到了第一个元素,任何建议请不要评论以上,因为我没有足够的代表;我更新了我的答案,以澄清仅获取第一个元素的原因。将回路移出回路。