2

mechanize の使い方を学ぶために、この小さなプロジェクトを作成することにしました。今のところ、urbandictionary に移動し、検索フォーム内に「skid」という単語を入力し、送信を押して HTML を出力します。

私がやりたいことは、最初の定義を見つけてそれを出力することです。どうすれば正確にそれを行うことができますか?

これはこれまでの私のソースコードです:

import mechanize

br = mechanize.Browser()
page = br.open("http://www.urbandictionary.com/")

br.select_form(nr=0)
br["term"] = "skid"
br.submit()

print br.response().read()

定義が保存される場所は次のとおりです。

<div class="definition">Canadian definition: Commonly used to refer to someone   who      stopped evolving, and bathing, during the 80&#x27;s hair band era.  Generally can be found wearing AC/DC muscle shirts, leather jackets, and sporting a <a href="/define.php?term=mullet">mullet</a>.  The term &quot;skid&quot; is in part derived from &quot;skid row&quot;, which is both a band enjoyed by those the term refers to, as well as their address.  See also <a href="/define.php?term=white%20trash">white trash</a> and <a href="/define.php?term=trailer%20park%20trash">trailer park trash</a></div><div class="example">The skid next door got drunk and beat up his old lady.</div>

div 定義内に格納されていることがわかります。ソース コード内の div を検索する方法は知っていますが、タグの間にあるすべてのものを取得して表示する方法がわかりません。

4

3 に答える 3

1

と言われたので、 BeautifulSoupで回答しようと思いました。最適なものを使用してください。

import bs4, urllib2

# Use urllib2 to get the html from the web
url     = r"http://www.urbandictionary.com/define.php?term={term}"
request = url.format(term="skid")
raw     = urllib2.urlopen(request).read()

# Convert it into a soup
soup    = bs4.BeautifulSoup(raw)

# Find the requested info
for word_def in soup.findAll(class_ = 'definition'):
    print word_def.string
于 2013-08-23T19:35:01.933 に答える
0

lxmlを使用して HTML フラグメントを解析できます。

import lxml.html as html
import mechanize

br = mechanize.Browser()
page = br.open("http://www.urbandictionary.com/")

br.select_form(nr=0)
br["term"] = "skid"
br.submit()

fragment = html.fromstring(br.response().read())

print fragment.find_class('definition')[0].text_content()

ただし、このソリューションは div 内の in タグを削除し、テキストを平坦化します。

于 2013-08-23T16:14:43.857 に答える