Python 在BeautifulSoup中将字典转换为列表

Python 在BeautifulSoup中将字典转换为列表,python,Python,如果'boa'在href中,如何将项目列表保存到列表中?我不想使用get()打印它们,而是将它们转换为自己变量中的列表(似乎它们在字典中?),最好是boat\u链接。谢谢 import urllib2 from bs4 import BeautifulSoup #Open Craigslist with BeautifulSoup and save to file url = 'http://losangeles.craigslist.org/boo/' response = urllib

如果
'boa'
href
中,如何将项目列表保存到列表中?我不想使用get()打印它们,而是将它们转换为自己变量中的列表(似乎它们在字典中?),最好是
boat\u链接
。谢谢

import urllib2
from bs4 import BeautifulSoup

#Open Craigslist with BeautifulSoup and save to file

url = 'http://losangeles.craigslist.org/boo/'

response = urllib2.urlopen(url)
webContent = response.read()

f = open('C:\Users\dell\Desktop\python\\boat_crawler\craigslist.html', 'w')
f.write(webContent)
f.close

html_doc = open('C:\Users\dell\Desktop\python\\boat_crawler\craigslist.html')

soup = BeautifulSoup(html_doc)

boat_links = []

for a in soup.find_all('a'):
    if 'boa' in a['href']:
    print a.get('href')

我不确定你是想要一个列表还是一本字典,或者一本列表字典,所以这里都是

if a.get('href').find('boa')>-1:
    boat_links.append(a.get('href'))
这是一个字典,其中标记文本作为键,href作为值

boat_links = {}
for a in soup.find_all('a'):
    if a.get('href').find('boa')>-1:
         boat_links[a.text] = a.get('href')
这是一个基于a.tags的列表字典(如果您有多个相同文本的链接怎么办)


boat_links=[a['href']表示汤中的a。如果a['href']中的'boa'表示“a”,则查找所有('a')。
谢谢!是否可以自己在
for
循环中执行此操作?
boat_links = {}
for a in soup.find_all('a'):
    if a.get('href').find('boa')>-1
         if boat_links.has_key(a.text):
              boat_links[a.text].append(a.get('href'))
         else:
              boat_links[a.text] = [a.get('href')]