Web挖掘或抓取或爬行?我应该使用什么工具/库?

Fla*_*ake 1 python java web-crawler web-scraping web-mining

我想抓取并将一些网页保存为HTML.比如说,爬进数百个热门网站,只需保存他们的前台和"关于"页面.

我已经查看了很多问题,但是没有从网页抓取或网页抓取问题中找到答案.

我应该使用什么库或工具来构建解决方案?或者甚至有一些现有的工具可以处理这个?

Rab*_*ski 6

在使用Python时,您可能对mechanizeBeautifulSoup感兴趣.

机械化类型模拟浏览器(包括代理,伪造浏览器标识,页面重定向等选项),并允许轻松获取表单,链接,...文档虽然有点粗糙/稀疏.

一些示例代码(来自mechanize网站)给你一个想法:

import mechanize
br = mechanize.Browser()
br.open("http://www.example.com/")
# follow second link with element text matching regular expression
html_response = br.follow_link(text_regex=r"cheese\s*shop", nr=1)
print br.title()
print  html_response
Run Code Online (Sandbox Code Playgroud)

BeautifulSoup允许很容易地解析html内容(你可以用机械化获取),并支持正则表达式.

一些示例代码:

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html_response)

rows = soup.findAll('tr')
for r in rows[2:]:  #ignore first two rows
    cols = r.findAll('td')
    print cols[0].renderContents().strip()    #print content of first column
Run Code Online (Sandbox Code Playgroud)

因此,上面的这10行几乎可以复制粘贴,以便打印网站上每个表行的第一列的内容.