简介
- y4 C4 G9 B6 e( Y% k% B AutoScraper 是使用 Python 实现的 Web 爬虫,兼容 Python 3,能快速且智能获取指定网站上的数据,这些数据可以是网页文本、URL 地址或者是其它 HTML 元素。另外,它还可以学习抓取规则并返回类似的元素。
, F) c0 F. Y' N1 Y! g* B4 S! u8 J 下载安装
: P- K8 ~: {/ j. ~" ` 项目的源码地址是:https://github.com/alirezamika/autoscraper 7 g$ r1 L/ i( e: ]+ O
兼容 Python 3。可使用以下方法进行安装:
# K$ F8 H: M; k7 D2 `" F: t9 K (1)从git获取安装 $ pip install git+https://github.com/alirezamika/autoscraper.git 5 I4 k8 P1 b7 a- [* R) n
(2)从PyPI获取安装 $ pip install autoscraper
$ Q( H" y3 N& x5 F3 R( \6 P (3)下载源码后进行安装 $ python setup.py install
7 p5 ]/ W" u4 ~% r' y+ e/ V: W 简单使用
8 q1 e4 `) Y! {7 R0 c6 G; n6 a 假设我们想在stackoverflow页面中获取所有相关的文章标题:
8 H% N+ a% \5 H, G" N" | 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) 输出结果如下:
& {# S$ f( L Z ~* k [
'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?'
]抓取相似结果
2 y8 w" H- V# g! T8 M 当你还想获取stackoverflow上其他页面中所有相关的文章标题,则可以直接通过get_result_similar方法获取:( Q$ B" S# ]$ U0 o2 ?! D
scraper.get_result_similar('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 两个页面的抓取结果为:
/ f. |8 L. m' {. A/ d# t
/ v2 m2 H0 P( P$ K( H3 x! H7 K$ q
抓取确切结果 6 L* t4 P( {/ y/ t3 E
当你只想抓取某个确切的结果,可以使用get_result_exact方法,即从wanted_list中以完全相同的顺序检索数据:4 {/ a9 G# N; j, X: u
scraper.get_result_exact('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 比如抓取页面中排第2的相关文章标题,执行结果:
. w$ \+ D1 E* l4 g
; a. g' c! M- {0 O7 [ 自定义请求模块参数 4 ]# v( u* I3 p9 {! ^
你还可以传递任何自定义请求模块参数。例如,你可能想使用代理或自定义头:
~& T) F9 o$ K2 T& @ X4 Q) s 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))抓取多项信息 $ G9 {4 k) _; ~$ B
假设我们想要抓取关于文本,Star的数量和Github回购页面的问题链接:6 e1 c1 \' |3 p3 B
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) 执行结果为:2 R, P& V; M- Z" }
" M# K, ]% [" v6 w8 \# _6 ]/ d" ~( O
保存模型
/ A. R3 y/ h# @ 我们可以保存抓取的模型以便以后使用:
) }+ l* G' u' ~( l2 G0 E # 指定保存的文件路径
scraper.save('stackoverflow')
# 调用方法:
scraper.load('stackoverflow') AutoScraper简单介绍就到这里了,如果你想使用更多的功能,详见官方主页了解。
3 Q$ ?2 H- a- l/ z7 C+ R3 g
1 O' @, }& M! V6 ^, t