开发高度并发的web刮板,很容易。

ragstoriches的Python项目详细描述


ragstoriches是一个组合的库/框架,可以方便地编写web scraper 使用gevent和请求。

一个简单的例子来讲述这个故事:

#!/usr/bin/env python# -*- coding: utf-8 -*-fromurlparseimporturljoinimportrefrombs4importBeautifulSoupfromragstoriches.scraperimportScraperrr=Scraper(__name__)@rr.scraperdefindex(requests,context,url='http://eastidaho.craigslist.org/search/act?query=+'):soup=BeautifulSoup(requests.get(url).text)forrowinsoup.find_all(class_='row'):yield'posting',context,urljoin(url,row.find('a').attrs['href'])nextpage=soup.find(class_='nextpage')ifnextpage:yield'index',context,urljoin(url,nextpage.find('a').attrs['href'])@rr.scraperdefposting(requests,context,url):soup=BeautifulSoup(requests.get(url).text)infos=soup.find(class_='postinginfos').find_all(class_='postinginfo')title=soup.find(class_='postingtitle').text.strip()id=re.findall('\d+',infos[0].text)[0]date=infos[1].find('date').text.strip()body=soup.find(id='postingbody').text.strip()printtitleprint'='*len(title)print'post *%s*, posted on %s'%(id,date)printbodyprint

使用pip install ragstoriches beautifulsoup4安装库和BeautifulSoup 4,然后将上述内容另存为craigs.py, 最后用ragstoriches craigs.py运行。

您将得到一堆混乱的输入,因此下一步是重定向stdout 文件:

ragstoriches craigs.py > output.md

尝试在命令行中为此scraper提供不同的url:

ragstoriches craigs.py http://newyork.craigslist.org/mnh/acc/  > output.md  # hustle
ragstoriches craigs.py http://orangecounty.craigslist.org/wet/ > output.md  # writing OC
ragstoriches craigs.py http://seattle.craigslist.org/w4m/      > output.md  # sleepless in seattle

有很多命令行选项可用,请参见ragstoriches --help 一份清单。

写入刮刀

scraper模块由一些初始化代码和 替补队员。scraping首先调用名为index的scraper moduel中的scraperrr(请参见上面的示例)。

参数requests应该像requests模块一样对待(它实际上是请求的实例 游泳池)。只要你用它来抓取网页,你就不用担心 关于阻塞或超过并发限制。

变量context是任意的,但是按照惯例是字典。是一个 将状态从一个刮刀传递到另一个刮刀或共享状态的方式。只是 由ragstoriches传递,没有其他接触。

url是要擦写和解析的url。

将忽略刮刀的返回值。但是,如果刮刀是发电机 (即包含yield语句),它产生的任何值都必须是3元组 由scraper的名称、上下文对象和另一个url组成。这些 添加到要刮除的作业队列中。

ragstoriches的好朋友是urlparse.urljoin函数 和BeautifulSoup4

用作库

不使用命令行也可以将ragstoriches用作库 工具,但只需导入一个scraper并使用^{tt14}运行它$ 方法。记得先用gevent修补。

有关详细信息,请参见源文件,因为没有太多文档 此时可用。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java允许具有不同父类的类扩展类,而无需多重继承   java如何创建动态化的JScrollPane w/JPanel作为客户端?   java如何组织和命名包   在Java中读取属性文件   java无法解释的Android意图行为   在Java中动态执行多个BPEL文件的部署   ssl Java 6 SNI(服务器名称指示)?   java我们可以使用Robot框架自动化web和移动应用程序来执行并行执行   java for star pettern的循环   java为什么BinaryReader在线程中,从netty读取错误的数据包?   在java中将华氏度转换为摄氏度   使用Spark和java处理空值和引号编写CSV文件   Java中已排序日期到块的列表   visual studio代码VSCode Java不是linting或自动完成局部变量,而是自动完成Java快捷方式,如“sysout”