0

'boa'がリストにある場合、アイテムのリストを保存するにはどうすればよいhrefですか? get() を使用してそれらを出力したくはありませんが、代わりにそれらを独自の変数のリストに変換します (これらは辞書にあるようです?)、できればboat_links. ありがとう!

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')
4

1 に答える 1

1

リストまたは辞書またはリストの辞書が必要かどうかわからないので、ここにそれらすべてを示します

if a.get('href').find('boa')>-1:
    boat_links.append(a.get('href'))

これは、 a タグ テキストをキーとし、 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 = {}
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')]
于 2013-06-21T19:47:06.183 に答える