通过网络表单提交数据并提取结果
我的python级别是新手。我从未写过网络抓取工具或搜寻器。我已经编写了python代码以连接到api并提取所需的数据。但是对于某些提取的数据,我想获得作者的性别。我找到了该网站,http://bookblog.net/gender/genie.php
但缺点是没有可用的api。我想知道如何编写python将数据提交到页面中的表单并提取返回数据。如果我能对此提供一些指导,那将是一个很大的帮助。
这是dom的形式:
<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
<input type="radio" value="nonfiction" name="genre">
nonfiction
<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>
-
无需使用机械化,只需在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')