[英]Assigning the output of a for loop to a variable
我正在嘗試將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
我希望此輸出的格式是此代碼的執行方式,但是所有這些頌歌都正確地打印出提取的鏈接:
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 ='>點擊此處,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” />,http://elink.tiffany.com/r/YB7DL5S/32FU1/5A6EIF/QFMQOO/T2WUY/52/h“ ='lucida =“” sans =“” style ='3D“ text-decoration:none;' unicode =“”> ENGAGEMENT,
您正在創建僅具有一個鍵的字典,該鍵對於循環的每次迭代都將被覆蓋。 也許列表更有意義?
urls = []
for x in soup.find_all('a', href=True):
urls.append(x)
您在字典中一直分配相同的鍵,這是您唯一的錯誤:
收集並放入列表中:
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
這應該可以按您希望的方式工作,希望能有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.