1

HTML ページを解析しようとしていますが、ページを解析する前に結果をフィルタリングする必要があります。

たとえば、'http://www.ksl.com/index.php?nid=443' は、ユタ州の自動車の機密リストです。すべての車を解析する代わりに、最初にフィルター処理 (つまり、すべての BMW を検索) してから、それらのページのみを解析したいと考えています。PythonでJavaScriptフォームに入力することは可能ですか?

これが私がこれまでに持っているものです:

import urllib

content = urllib.urlopen('http://www.ksl.com/index.php?nid=443').read()
f = open('/var/www/bmw.html',"w")
f.write(content)
f.close()
4

2 に答える 2

2

これがその方法です。最初にページをダウンロードし、スクレイピングして探しているモデルを見つけます。次に、スクレイピングする新しいページへのリンクを取得できます。ここでは JavaScript は必要ありません。このモデルと BeautifulSoup のドキュメンテーションを参考にしてください。

from BeautifulSoup import BeautifulSoup
import urllib2

base_url = 'http://www.ksl.com'
url = base_url + '/index.php?nid=443'
model = "Honda" # this is the name of the model to look for

# Load the page and process with BeautifulSoup
handle = urllib2.urlopen(url)
html = handle.read()
soup = BeautifulSoup(html)

# Collect all the ad detail boxes from the page
divs = soup.findAll(attrs={"class" : "detailBox"})

# For each ad, get the title
# if it contains the word "Honda", get the link
for div in divs:
    title = div.find(attrs={"class" : "adTitle"}).text
    if model in title:
        link = div.find(attrs={"class" : "listlink"})["href"]
        link = base_url + link
        # Now you have a link that you can download and scrape
        print title, link
    else:
        print "No match: ", title

回答の時点で、このコード スニペットは Honda モデルを探しており、次の結果を返します。

1995-  Honda Prelude http://www.ksl.com/index.php?sid=0&nid=443&tab=list/view&ad=8817797
No match:  1994-  Ford Escort
No match:  2006-  Land Rover Range Rover Sport
No match:  2006-  Nissan Maxima
No match:  1957-  Volvo 544
No match:  1996-  Subaru Legacy
No match:  2005-  Mazda Mazda6
No match:  1995-  Chevrolet Monte Carlo
2002-  Honda Accord http://www.ksl.com/index.php?sid=0&nid=443&tab=list/view&ad=8817784
No match:  2004-  Chevrolet Suburban (Chevrolet)
1998-  Honda Civic http://www.ksl.com/index.php?sid=0&nid=443&tab=list/view&ad=8817779
No match:  2004-  Nissan Titan
2001-  Honda Accord http://www.ksl.com/index.php?sid=0&nid=443&tab=list/view&ad=8817770
No match:  1999-  GMC Yukon
No match:  2007-  Toyota Tacoma
于 2012-05-03T20:34:09.117 に答える
-1

Python を使用している場合は、Beautifull Soupが探しているものです。

于 2012-05-03T19:45:45.993 に答える