2011-12-04 12 views
11

私のpythonレベルは初心者です。私は決してWebスクレーパーやクローラーを書いたことはありません。私はapiに接続し、私が望むデータを抽出するためのPythonコードを書いています。しかし、抽出されたデータの中には、著者の性別を取得したいものもあります。私はこのウェブサイトhttp://bookblog.net/gender/genie.phpを見つけましたが、欠点は利用可能なAPIがないことです。私はページ内のフォームにデータを送信し、戻り値のデータを抽出するためのPythonを書く方法を知りました。もし私がこれについていくつかの指針を得ることができれば、大きな助けになるでしょう。Webフォームからデータを送信し、結果を抽出します。

<form action="analysis.php" method="POST"> 
<textarea cols="75" rows="13" name="text"></textarea> 
<div class="copyright">(NOTE: The genie works best on texts of more than 500 words.)</div> 
<p> 
<b>Genre:</b> 
<input type="radio" value="fiction" name="genre"> 
fiction&nbsp;&nbsp; 
<input type="radio" value="nonfiction" name="genre"> 
nonfiction&nbsp;&nbsp; 
<input type="radio" value="blog" name="genre"> 
blog entry 
</p> 
<p> 
</form> 

結果ページのDOM::

<p> 
<b>The Gender Genie thinks the author of this passage is:</b> 
male! 
</p> 

答えて

22

mechanizeを使用する必要はありません。POSTリクエストで正しいフォームデータを送信するだけです。

また、正規表現を使用してHTMLを解析することは悪い考えです。 lxml.htmlのようなHTMLパーサーを使う方が良いでしょう。

import requests 
import lxml.html as lh 


def gender_genie(text, genre): 
    url = 'http://bookblog.net/gender/analysis.php' 
    caption = 'The Gender Genie thinks the author of this passage is:' 

    form_data = { 
     'text': text, 
     'genre': genre, 
     'submit': 'submit', 
    } 

    response = requests.post(url, data=form_data) 

    tree = lh.document_fromstring(response.content) 

    return tree.xpath("//b[text()=$caption]", caption=caption)[0].tail.strip() 


if __name__ == '__main__': 
    print gender_genie('I have a beard!', 'blog') 
+0

私はeasy_install lxml.htmlをやってみましたが、次のエラーが発生しましたeasy_install lxml.html lxml.htmlを検索中 http://pypi.python.org/simple/lxml .html/ 'lxml.html'のインデックスページが見つかりませんでした(スペルが間違っている可能性があります) すべてのパッケージのインデックスをスキャンしています(少し時間がかかる場合があります) http://pypi.python.org/simple/ いいえローカルパッケージまたはlxml.htmlのダウンロードリンク エラー:Requirement.parse( 'lxml.html')の適切な配布が見つからない –

+1

モジュールのインポートでは、2つの名前の間に '.'があると、 2番目の名前は前の名前の範囲内です。インストールするモジュールはlxmlです。 – Acorn

+0

コメントした後に私はそれを実現しました。ありがとうagianl –

1

あなたは詳細についてはexamplesを参照してください、mechanizeを使用することができます

これは、フォームのDOMです。

from mechanize import ParseResponse, urlopen, urljoin 

uri = "http://bookblog.net" 

response = urlopen(urljoin(uri, "/gender/genie.php")) 
forms = ParseResponse(response, backwards_compat=False) 
form = forms[0] 

#print form 

form['text'] = 'cheese' 
form['genre'] = ['fiction'] 

print urlopen(form.click()).read() 
+0

お返事ありがとうございます。 machanizeのような音が私がインストールしたモジュールですか?ターミナルで素早くテストされ、モジュールエラーはありません。私はマックではない、私はeasy_installを行うことができなければならないmachanizeを取得します。 –

+0

あ、そうです、それは外部モジュールです。はい、あなたはeasy_install機械化を行うことができます。 –

15

あなたは提出してコンテンツを取得するためにmechanizeを使用して、あなたが望むものを得るためのreモジュールできます。たとえば、以下のスクリプトはあなたの質問のテキストのためにそれを行います:

import re 
from mechanize import Browser 

text = """ 
My python level is Novice. I have never written a web scraper 
or crawler. I have written a python code to connect to an api and 
extract the data that I want. But for some the extracted data I want to 
get the gender of the author. I found this web site 
http://bookblog.net/gender/genie.php but downside is there isn't an api 
available. I was wondering how to write a python to submit data to the 
form in the page and extract the return data. It would be a great help 
if I could get some guidance on this.""" 

browser = Browser() 
browser.open("http://bookblog.net/gender/genie.php") 

browser.select_form(nr=0) 
browser['text'] = text 
browser['genre'] = ['nonfiction'] 

response = browser.submit() 

content = response.read() 

result = re.findall(
    r'<b>The Gender Genie thinks the author of this passage is:</b> (\w*)!', content) 

print result[0] 

何がしますか? (それが初めてとなる、充填すべき一形態のみが存在するため)

browser = Browser() 
browser.open("http://bookblog.net/gender/genie.php") 

が、それは形式を選択します:それはmechanize.Browserを作成し、指定されたURLに行くまた

browser.select_form(nr=0) 

、それは...の形式のエントリを設定します

browser['text'] = text 
browser['genre'] = ['nonfiction'] 

...そして、それを提出する:

response = browser.submit() 

今、我々は結果を得る:

content = response.read() 

我々は結果が形になっていることを知っている:

<b>The Gender Genie thinks the author of this passage is:</b> male! 

だから我々は、マッチングのための正規表現を作成し、re.findall()を使用します。

result = re.findall(
    r'<b>The Gender Genie thinks the author of this passage is:</b> (\w*)!', 
    content) 

結果はご利用いただけます:

print result[0] 
+0

ありがとう、これは私の大きな説明のような新しいBのための素晴らしい答えです。私は1回以上upvoteすることができます..;) –

関連する問題