在python中从列表创建元组列表
我正在使用python中的在python中从列表创建元组列表,python,list,beautifulsoup,tuples,urllib2,Python,List,Beautifulsoup,Tuples,Urllib2,我正在使用python中的urllib2模块从一些URL(如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(htm
urllib2
模块从一些URL(如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(indicators)是一个数组。坦率地说,我只想使用此列表在某些网页的模板上呈现,但面临许多错误,如“ascii”编解码器无法对0-4位的字符进行编码:序号不在范围内(128),那么,如何避免这些错误呢?@shivakrishna——我认为你应该发布一个关于呈现数据的单独问题,包括你正在使用的相关代码和你得到的确切错误……当然,这些问题可能包含与询问错误为何正确显示相同的代码?,因为你们已经知道这里发生了什么。。。。无论如何,我会尝试提出一个新问题:)口述不是更好吗??(用于储存)