gpt4 book ai didi

python - 通过网络表单提交数据并提取结果

转载 作者:太空狗 更新时间:2023-10-29 16:59:51 25 4
gpt4 key购买 nike

我的 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&nbsp;&nbsp;
<input type="radio" value="nonfiction" name="genre">
nonfiction&nbsp;&nbsp;
<input type="radio" value="blog" name="genre">
blog entry
</p>
<p>
</form>

结果页面d​​om:

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

最佳答案

无需使用 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')

关于python - 通过网络表单提交数据并提取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8377055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com