使用python、BeautifulSoup、mechanize设置HTML文本区域内容(没有表单,只有divs)

使用python、BeautifulSoup、mechanize设置HTML文本区域内容(没有表单,只有divs),python,forms,textarea,beautifulsoup,mechanize,Python,Forms,Textarea,Beautifulsoup,Mechanize,我正在尝试填写一个包含textarea元素的表单。我正在将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”,但一旦

我正在尝试填写一个包含textarea元素的表单。我正在将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标记之间没有内容:

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>
有人知道为什么会出现unicode错误吗?显然,我的
soup
对象不仅仅是一个unicode字符串,因为我成功地使用了
.find

解决方案:
Vladimir的解决方案是正确的,但现实世界的HTML可能会在BeautifulSoup 3.1()中生成格式不正确的开始标记。
错误。在降级到BeautifulSoup 3.0.8后,一切正常。当我发布最初的问题时,我不得不做一些陪审团操纵,以使mechanize成为
read()
插入到BeautifulSoup对象中,以避免出现格式不正确的开始标记
错误。这导致创建一个uencode sting而不是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>'
从美化组导入美化组
汤=美汤(“”)
soup.find('textarea',{'name':'classified_description'})。插入(0,'value')
断言str(soup)=“值”

详细描述此类转换。

谢谢!您的示例对我很有用,但生产代码抛出了一个错误:
AttributeError:“unicode”对象没有属性“previousSibling”
。了解原因吗?在代码的某个地方,某些函数返回
unicode
,而您希望它返回soup标记对象。请尝试调试顺便说一句,如果你也接受答案,那就更好了;)我希望我没有因为没有马上把你的回答标记为答案而粗鲁。问题一直存在,所以我一直等到完全解决。我现在理解了Beautifulsoup3.1中的一个bug(参见我的文章编辑)。您的答案是更好地构建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>'