【问题标题】:How to write a Python robot that browses [duplicate]如何编写一个浏览的 Python 机器人 [重复]
【发布时间】:2011-04-05 06:16:28
【问题描述】:

可能重复:
Where shall I start in making a scraper or a bot using python?

我知道这显然是可能的...... 我被要求实现某种机器人,它可以访问网站、登录、访问一组链接、填写带有日期输入的搜索表单以获取 XLS 文件并注销。 如果手动完成,整个过程几乎需要一个小时,所以脚本/机器人可以为我们节省很多时间。

想法?图书馆?我想我需要 urllib?
或者可能根本不使用 Python?
提前致谢!

编辑:我搜索了很多“python crawler”,直到 cmets 之前才发现 Mechanize 或 Scrapy:/
我将首先进一步研究机械化。谢谢。

【问题讨论】:

标签: python robot


【解决方案1】:

我是twill python 模块的粉丝。这是我不久前用来进行基本浏览和抓取的一小部分代码示例。

import twill
import twill.commands as c

def login():
    c.clear_cookies()
    c.go('http://icfpcontest.org/icfp10/login')
    c.fv(1, 'j_username', 'Side Effects May Include...')
    c.fv(1, 'j_password', '<redacted>')
    c.submit()
    c.save_cookies('/tmp/icfp.cookie')

all_cars_rx = re.compile(r'<td style="width: 20%;">(\d+)</td><td>(\d+)</td>')
def list_cars():
    c.go('http://icfpcontest.org/icfp10/score/instanceTeamCount')
    cars = re.findall(all_cars_rx, c.show())
    if not cars:
        sys.stderr.write(c.show())
        sys.stderr.write('Could not find any cars')
    return cars;

值得一提的是,应该使用正则表达式来解析 HTML。您在这里看到的是在很短的时间内为 ICFP 完成的肮脏黑客攻击。

【讨论】:

    【解决方案2】:

    最近我发现了PhantomJS 并将其用于类似的任务。它是命令行 JavaScript 解释器,内置了功能齐全的 Webkit 引擎。恕我直言,对于像您这样的任务来说,它确实是一款易于使用的工具,并且您拥有使用 Firebug 所说的各种可编写脚本的功能。它还具有用于截取屏幕截图并将其保存到图像文件的内置调用。

    【讨论】:

      猜你喜欢
      • 2011-02-27
      • 2015-05-27
      • 2020-07-25
      • 1970-01-01
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多