将for循环的输出分配给变量

时间:2013-10-11 02:21:57

标签: python for-loop dictionary beautifulsoup

我正在尝试将for循环的输出分配给变量或字典,但是现在我只能得到它来打印循环的第一次迭代,它甚至不是正确的格式。

这是我的代码:

result, data = mail.uid('search', None, "(FROM 'tiffany@e.tiffany.com')") # search and return uids instead
latest_email_uid = data[0].split()[-1]
result, data = mail.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = data[0][1]

html = raw_email
soup = BS(html)
pretty_email = soup.prettify('utf-8')

urls={}
for x in soup.find_all('a', href=True):
    urls['href'] = x

print urls

我希望这个代码的输出格式是这个代码的执行方式,但所有这些odes都正确地打印出提取的链接:

result, data = mail.uid('search', None, "(FROM 'tiffany@e.tiffany.com')") # search and return uids instead
latest_email_uid = data[0].split()[-1]
result, data = mail.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = data[0][1]

html = raw_email
soup = BS(html)
pretty_email = soup.prettify('utf-8')

for urls in soup.find_all('a', href=True):
    print urls['href']

print urls

谢谢!

编辑:

我希望它打印的方式是:

3D"http://elink.tiffany.com/r/YB7DL5S/32FU1/5A6EIF/QFMQOO/9SUZ8/52/h"=
3D"http://elink.tiffany.com/r/YB7DL5S/32FU1/5A6EIF/QFMQOO/N8ASK/52/h"=
3D"http://elink.tiffany.com/r/YB7DL5S/32FU1/5A6EIF/QFMQOO/DNH42/52/h"=
3D"http://elink.tiffany.com/r/YB7DL5S/32FU1/5A6EIF/QFMQOO/T2WPJ/52/h"=
3D"http://elink.tiffany.com/r/YB7DL5S/32FU1/5A6EIF/QFMQOO/PO7RQ/52/h"=
3D"http://elink.tiffany.com/r/YB7DL5S/32FU1/5A6EIF/QFMQOO/BRLMA/52/h"=
3D"http://elink.tiffany.com/r/YB7DL5S/32FU1/5A6EIF/QFMQOO/N8ASQ/52/h"=
3D"http://elink.tiffany.com/r/YB7DL5S/32FU1/5A6EIF/QFMQOO/SV4PN/52/h"=
3D"http://elink.tiffany.com/r/YB7DL5S/32FU1/5A6EIF/QFMQOO/RC53N/52/h"=
3D"http://elink.tiffany.com/r/YB7DL5S/32FU1/5A6EIF/QFMQOO/7Q3AA/52/h"=

使用下面的解决方案我可以得到这个:

http://elink.tiffany.com/r/YB7DL5S/32FU1/5A6EIF/QFMQOO/1XF33/52/h?='n:underline =“”style ='3D“text-decoratio ='> click在这里,http://elink.tiffany.com/r/YB7DL5S/32FU1/5A6EIF/QFMQOO/6EN2U/52/h"='target ='3D“_blank”'> http://eimg.tiffany.com/ mbs_tiffanyc / Standard / Logoblue.gif“'title ='3D”Tiffany'wi =“dth = 3D147”/&gt ;, http://elink.tiffany.com/r/YB7DL5S/32FU1/5A6EIF/QFMQOO/T2WUY/52 / h“='lucida =”“sans =”“style ='3D”text-decoration:none;'的unicode = “” >接合时,

2 个答案:

答案 0 :(得分:1)

您正在创建一个只有一个键的dict,您可以为循环的每次迭代覆盖它。也许列表更有意义?

urls = []
for x in soup.find_all('a', href=True):
    urls.append(x)

答案 1 :(得分:1)

你继续指定dict中的同一个键,这是你唯一的错误:

收集并将其列入清单:

urls=[]
for x in soup.find_all('a', href=True):
    urls.append(x['href'])
print urls

或者进入字典:

urls={}
search = soup.find_all('a', href=True)
for x in range(len(search)):
    urls[x] = search[x]['href'] ##Result is: {0:firsturl, 1:secondurl, 2:thirdurl}
    ##and so on

这应该按照您的意愿运行,希望这会有所帮助!

相关问题