[英]Create a list of tuples from list in python
我在python中使用urllib2
模塊從http://www.google.co.in/
等一些網址中的錨標記中獲取某種信息,下面是代碼
import urllib2
import urlparse
from BeautifulSoup import BeautifulSoup
url = "http://www.google.co.in/"
page = urllib2.urlopen(url)
html = page.read()
page.close()
soup = BeautifulSoup(html)
for tag in soup.findAll('a', href=True):
text = tag.text
tag['href'] = urlparse.urljoin(url, tag['href'])
print ' '.join([text,tag['href']])
結果:
Web History http://www.google.co.in/history/optout?hl=en
Settings http://www.google.co.in/preferences?hl=en
Sign in https://accounts.google.com/ServiceLogin?hl=en&continue=http://www.google.co.in/
Advanced search http://www.google.co.in/advanced_search?hl=en-IN&authuser=0
Language tools http://www.google.co.in/language_tools?hl=en-IN&authuser=0
.......................
現在很好,但我想將信息存儲為下面的元組列表
[('Web History','http://www.google.co.in/history/optout?hl=en'),('Settings','http://www.google.co.in/preferences?hl=en'),('Sign in','https://accounts.google.com/ServiceLogin?hl=en&continue=http://www.google.co.in/')................]
所以任何人都可以讓我知道我們如何格式化來自for循環的數據作為上面的元組列表
嘗試這樣的事情:
[(tag.text, urlparse.urljoin(url, tag['href']))
for tag in soup.findAll('a', href=True)]
你可以嘗試創建一個哈希並從中提取items()
元組,這只是一個hack:
def __init__(self, *args, **kwargs):
super(IndicatorForm, self).__init__(*args, **kwargs)
d = dir(indicators)
b = {}
for a in d:
b[a] = a
b = b.items()
b.sort()
self.fields["choice"].choices = b
這里dir(指標)是一個數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.