简介 ) V! B* u, i' z
AutoScraper 是使用 Python 实现的 Web 爬虫,兼容 Python 3,能快速且智能获取指定网站上的数据,这些数据可以是网页文本、URL 地址或者是其它 HTML 元素。另外,它还可以学习抓取规则并返回类似的元素。- b- g+ T& l! Z1 |2 u- z
下载安装 2 n$ D b8 M; G( d
项目的源码地址是:https://github.com/alirezamika/autoscraper
/ J$ U" `; G: F! a 兼容 Python 3。可使用以下方法进行安装:
! G( W/ t! {0 i% F/ D9 U7 t (1)从git获取安装 $ pip install git+https://github.com/alirezamika/autoscraper.git
6 Q1 e8 j$ B3 ] (2)从PyPI获取安装 $ pip install autoscraper, J! T" Q) N7 [
(3)下载源码后进行安装 $ python setup.py install$ `5 r( a7 p5 r
简单使用
: e8 Q% d& W0 R) F, F 假设我们想在stackoverflow页面中获取所有相关的文章标题:
) g+ g6 b$ e! n1 r9 ? from autoscraper import AutoScraper
url = 'https://stackoverflow.com/questions/2081586/web-scraping-with-python'
wanted_list = ["How to call an external command?"]
scraper = AutoScraper()
result = scraper.build(url, wanted_list)
print(result) 输出结果如下:; s3 }7 H2 P' f
[
'How do I merge two dictionaries in a single expression in Python (taking union of dictionaries)?',
'How to call an external command?',
'What are metaclasses in Python?',
'Does Python have a ternary conditional operator?',
'How do you remove duplicates from a list whilst preserving order?',
'Convert bytes to a string',
'How to get line count of a large file cheaply in Python?',
"Does Python have a string 'contains' substring method?",
'Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?'
]抓取相似结果
7 }0 }6 h o( M2 K& [! b% ]: f. h( {7 | 当你还想获取stackoverflow上其他页面中所有相关的文章标题,则可以直接通过get_result_similar方法获取:
9 u9 B9 `5 g% A$ I scraper.get_result_similar('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 两个页面的抓取结果为:
" y" u6 x/ a) K0 q
% v% Z$ B0 ]+ ~, ~ E) M! A
抓取确切结果 2 e# _+ _+ z" H9 I( L) K
当你只想抓取某个确切的结果,可以使用get_result_exact方法,即从wanted_list中以完全相同的顺序检索数据:: u3 u& G% V; `
scraper.get_result_exact('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 比如抓取页面中排第2的相关文章标题,执行结果:# d& A0 s0 S6 O5 n5 ~$ l# `8 a$ R
# o8 p7 y5 E) i0 C* K0 H
自定义请求模块参数 - H; L+ g3 G9 X: A; [0 Z2 w' D
你还可以传递任何自定义请求模块参数。例如,你可能想使用代理或自定义头:
! f$ g. ~- }' d' @) |# F+ } proxies = {
"http": 'http://127.0.0.1:8001',
"https": 'https://127.0.0.1:8001',
}
result = scraper.build(url, wanted_list, request_args=dict(proxies=proxies))抓取多项信息 - y! _ ~: t, a" q5 h3 c E
假设我们想要抓取关于文本,Star的数量和Github回购页面的问题链接:
6 T* R1 h2 P* N0 c' O- q8 t from autoscraper import AutoScraper
url = 'https://github.com/alirezamika/autoscraper'
wanted_list = ['A Smart, Automatic, Fast and Lightweight Web Scraper for Python', '2.5k', 'https://github.com/alirezamika/autoscraper/issues']
scraper = AutoScraper()
scraper.build(url, wanted_list) 执行结果为:6 Z9 H- h1 H* ]/ \
4 L2 u G- e- V/ Y# \; l 保存模型
5 C7 {3 C8 O5 W \$ M 我们可以保存抓取的模型以便以后使用:5 a: `9 r+ m% x H! a3 k
# 指定保存的文件路径
scraper.save('stackoverflow')
# 调用方法:
scraper.load('stackoverflow') AutoScraper简单介绍就到这里了,如果你想使用更多的功能,详见官方主页了解。; V% O) N: j0 D" d7 v7 M3 U/ A
; g7 I, j1 `5 C. e2 A# @+ U