【发布时间】:2011-06-10 20:46:45
【问题描述】:
我想提交登录 Reddit.com 网站,导航到页面的特定区域,然后提交评论。我看不出这段代码有什么问题,但它不起作用,因为 Reddit 网站上没有反映任何变化。
import mechanize
import cookielib
def main():
#Browser
br = mechanize.Browser()
# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
#Opens the site to be navigated
r= br.open('http://www.reddit.com')
html = r.read()
# Select the second (index one) form
br.select_form(nr=1)
# User credentials
br.form['user'] = 'DUMMYUSERNAME'
br.form['passwd'] = 'DUMMYPASSWORD'
# Login
br.submit()
#Open up comment page
r= br.open('http://www.reddit.com/r/PoopSandwiches/comments/f47f8/testing/')
html = r.read()
#Text box is the 8th form on the page (which, I believe, is the text area)
br.select_form(nr=7)
#Change 'text' value to a testing string
br.form['text']= "this is an automated test"
#Submit the information
br.submit()
这是怎么回事?
【问题讨论】:
-
尝试添加至少 10 秒的睡眠。您还应该检查浏览器中的表单(不是“查看源代码”,而是 Chrome 中的“检查元素”或 FF 中的类似内容)并与下载的 HTML 进行比较。它可能有由 JS 动态填充的字段。
-
对了,Reddit 有一个 API,这样不是更好吗?
-
嗯,让我尝试添加睡眠。我不确定如何使用 API,因为没有提交 cmets 的文档。
-
编辑:尝试睡眠。没用。
标签: python networking screen-scraping mechanize