python - 使用 python、BeautifulSoup、mechanize 设置 HTML textarea 内容(没有表单,只有 div)

标签 python forms textarea beautifulsoup mechanize

我正在尝试填写包含文本区域元素的表单。我将 Python 与 BeautifulSoap 和 mechanize 模块一起使用(停留在 FreeBSD 8.1 上的 2.6.5,FreeBSD 存储库中的最新模块:BeautifulSoup 3.1.0.1 和 mechanize 0.2.1)。

BeautifulSoap 的问题是它没有正确设置 textarea 内容(我可以尝试 soup.textarea.insert(0, "FOO") 甚至 soup.textarea.contents = "FOO" ,但是一旦我用 soup.textarea 检查当前值,我仍然看到旧的 HTML 标签没有它们之间的内容:

<textarea name="classified_description" class="classified_textarea_text"></textarea>

mechanize 的问题在于它似乎只对真实形式进行操作。根据我在下面解析的 HTML,这实际上不是一个表单,而是一组内部包含输入项的 div。

我如何使用 Python 或这些模块中的任何一个来设置此 textarea 元素的值?

<div class="classified_field">
            <div class="classified_input_label">Description</div>
            <div class="classified_textarea_div">
                <textarea name="classified_description" id="classified_description" class="classified_textarea_text"></textarea>
            </div>
            <div class="site_clear"></div>
        </div>

我在下面尝试了 Vladimir 的技术,虽然它适用于他的示例,但出于某种原因它在我的生产代码中不起作用。我可以使用 .find()得到textarea ,但是 .insert()让我悲伤。这是我到目前为止所拥有的:

>>> soup.find('textarea', {'name': 'classified_description'})                  
<textarea name="classified_description" class="classified_textarea_text"></textarea>
>>> soup.find('textarea', {'name': 'classified_description'}).insert(0, "some text here")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.6/site-packages/BeautifulSoup.py", line 233, in insert
  newChild.nextSibling.previousSibling = newChild
AttributeError: 'unicode' object has no attribute 'previousSibling'
>>> 

任何人都知道为什么这会通过 unicode 错误?显然我的soup object 不仅仅是一个 unicode 字符串,因为我成功地使用了 .find .

解决方案: Vladimir 的解决方案是正确的,但现实世界的 HTML 可能会生成 malformed start tag BeautifulSoup 3.1 中的错误(official reason here)。降级到 BeautifulSoup 3.0.8 后,一切正常。当我发布最初的问题时,我不得不进行一些陪审团操纵以 Mechanize 到 read()。进入 BeautifulSoup 对象,以免获取 malformed start tag错误。这导致创建一个 uencode 字符串而不是 BeautifulSoup 对象。使用较旧的 BeautifulSoup 更正我的 Mechanize 代码导致了预期的行为。

最佳答案

这是一个使用 BeautifulSoup 的例子:

from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup('<textarea name="classified_description"></textarea>')
soup.find('textarea', {'name': 'classified_description'}).insert(0, 'value')
assert str(soup) == '<textarea name="classified_description">value</textarea>'

BeautifulSoup documentation on modifying the parse tree详细描述了此类转换。

关于python - 使用 python、BeautifulSoup、mechanize 设置 HTML textarea 内容(没有表单,只有 div),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11919924/

相关文章:

javascript - 使用 php 提交表单数据而不重新加载页面?

html - 输入值与标签值不一致

html - 跨浏览器与边距不一致?

python - 双对数图上的线性拟合不是线性的

Python模块wx不播放音频声音

javascript - 如何在提交时调用 javascript 函数来为输入赋值? (ACE编辑)

css - 如何更改 Disqus 评论文本区域中的文本颜色?

python - 将 Pandas Dataframe 中的特定列添加到另一个 Pandas Dataframe

python - 为什么在 celery 任务后不关闭日志文件

html - Textarea 标签在 Firefox 中生成两行而不是一行,但在 Chrome 中效果很好