使用Python mechanize

时间:2015-11-21 12:14:30

标签: python mechanize

我尝试使用Python机制化使用txt文件中的文本来填充Web表单,但是当填写表单时,所有返回字符/换行符都将丢失。有办法解决这个问题吗?当打印到控制台时它包含了回报,所以我有点难过。

def load_message():
the_message = open('ra_message.txt', 'r')
message = the_message.read()
the_message.close()
return message

def message(to_user, subject, the_message):
try:
    br.open(ra_message)
    br.select_form(nr=0)
    br['addrecipient'] = to_user
    br['subject'] = subject
    br['message'] = the_message
    br.submit()
    print('{} succesfully messaged.'.format(to_user))        
    save_line = to_user + ', TRUE\n'
    save_file = open('messaged_users.csv', 'a')
    save_file.write(save_line)
    save_file.close()
except Exception, e:
    print str(e)

def main():
try:
    the_message = load_message()
    login(username, password)
    for name in users:
        message(name, 'Hi {}'.format(name), the_message.format(vote_link))
    print('All users succesfully messaged.')
except Exception, e:
    print str(e)

1 个答案:

答案 0 :(得分:0)

经过一番挖掘后,我在另一个Stack Overflow线程中找到了答案 - https://stackoverflow.com/a/9461440/5588987

CR = \ r \ nLF = \ n

HTML表单采用换行符作为CRLF,因此:

\ r \ n有效!