简介
4 t! U, m' f; Z; Y! [5 l$ C0 z AutoScraper 是使用 Python 实现的 Web 爬虫,兼容 Python 3,能快速且智能获取指定网站上的数据,这些数据可以是网页文本、URL 地址或者是其它 HTML 元素。另外,它还可以学习抓取规则并返回类似的元素。
+ t6 ^8 _" U$ `3 [# [+ R9 |) e: h 下载安装 ; L0 I# e$ }- W+ U
项目的源码地址是:https://github.com/alirezamika/autoscraper ( N. G! ~" p+ o; X- E# n
兼容 Python 3。可使用以下方法进行安装:
& D9 X* q6 j6 a# n# n8 G. y (1)从git获取安装 $ pip install git+https://github.com/alirezamika/autoscraper.git : |1 \4 X4 x# }/ w0 K# v- _4 S a% _
(2)从PyPI获取安装 $ pip install autoscraper& D9 g9 Z8 v! B! {! m
(3)下载源码后进行安装 $ python setup.py install. d" c: @( t. }3 T- Y6 M4 d
简单使用 * ^! M: b; N6 o& W4 y P( E
假设我们想在stackoverflow页面中获取所有相关的文章标题:8 E. c. N9 L) R8 {7 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) 输出结果如下:+ q" U0 R! T" r& A/ _6 J2 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?'
]抓取相似结果
6 s2 X* K8 K. u5 T3 l& s 当你还想获取stackoverflow上其他页面中所有相关的文章标题,则可以直接通过get_result_similar方法获取:/ D3 C) _8 H6 \1 e& c9 j: k
scraper.get_result_similar('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 两个页面的抓取结果为:
# }* n* W( s) B2 T
# j! Q; C4 Z- |* h# m! i
抓取确切结果 5 F: w* c0 A1 p5 s# f
当你只想抓取某个确切的结果,可以使用get_result_exact方法,即从wanted_list中以完全相同的顺序检索数据:
5 b& L/ B6 [" y# {% O5 L) y/ |, q! i scraper.get_result_exact('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 比如抓取页面中排第2的相关文章标题,执行结果:
* d% s$ @1 P- C5 u- n8 P
T- _ L* a3 u d0 t2 P, Y9 o
自定义请求模块参数
4 A# v; B( ?' }+ T 你还可以传递任何自定义请求模块参数。例如,你可能想使用代理或自定义头:
. ]# p0 B% ]9 \ 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))抓取多项信息 3 W; }4 U7 O, [( e
假设我们想要抓取关于文本,Star的数量和Github回购页面的问题链接:
& e. h1 U& g* R 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) 执行结果为:0 c1 y) a) F8 s. p; F3 m% G
1 l$ d8 B) D! t5 n. [+ R 保存模型
# Z% k6 ]* c; e2 b! q" e 我们可以保存抓取的模型以便以后使用:( T( C" _5 I* X/ t* }7 e
# 指定保存的文件路径
scraper.save('stackoverflow')
# 调用方法:
scraper.load('stackoverflow') AutoScraper简单介绍就到这里了,如果你想使用更多的功能,详见官方主页了解。
. W# [) G& A* j% p8 l- W6 J5 j9 P" f ) u( K* I6 C* p' h0 ?