简介 * i2 r3 z0 ?2 @8 w" o: l) r9 t( ]- R. [
AutoScraper 是使用 Python 实现的 Web 爬虫,兼容 Python 3,能快速且智能获取指定网站上的数据,这些数据可以是网页文本、URL 地址或者是其它 HTML 元素。另外,它还可以学习抓取规则并返回类似的元素。
% M. Y& j7 v) _( P 下载安装 5 `; e% U9 x! r: u0 K1 i
项目的源码地址是:https://github.com/alirezamika/autoscraper 6 B" B- Z& O+ f. q# P3 O; b- {
兼容 Python 3。可使用以下方法进行安装:
% E4 J+ C2 y5 @ (1)从git获取安装 $ pip install git+https://github.com/alirezamika/autoscraper.git 0 a6 j5 W3 F4 Z2 q6 S
(2)从PyPI获取安装 $ pip install autoscraper
. w5 Y/ U1 u; R; D (3)下载源码后进行安装 $ python setup.py install( A4 n; E8 {# J1 p. s5 N" N4 C$ P
简单使用
8 w0 R; I) F! C, d5 _- x 假设我们想在stackoverflow页面中获取所有相关的文章标题:2 G+ @5 E" N( m- N0 H: o
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) 输出结果如下:
2 W& n4 I; H; @, a) o2 o [
'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?'
]抓取相似结果 : S; K5 _! L2 w; U5 k" f- x* j9 Y
当你还想获取stackoverflow上其他页面中所有相关的文章标题,则可以直接通过get_result_similar方法获取:; B! K% S8 `+ N% ~
scraper.get_result_similar('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 两个页面的抓取结果为:
. {4 V' V& Y0 N6 h) [" B
# B5 Y3 T' `) C1 E4 e" e/ `: M 抓取确切结果
" s8 U3 |% H/ _ 当你只想抓取某个确切的结果,可以使用get_result_exact方法,即从wanted_list中以完全相同的顺序检索数据:" x6 g: T1 Y0 \( d
scraper.get_result_exact('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 比如抓取页面中排第2的相关文章标题,执行结果:1 ~. V) U9 c5 y# `' I7 O# U
( ?' ~# z# g4 G: S 自定义请求模块参数 3 B5 H- [- f; J6 l/ C& E& V
你还可以传递任何自定义请求模块参数。例如,你可能想使用代理或自定义头:+ B, j* V m! v" U+ Q1 H' R& x
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))抓取多项信息 0 V6 o# g; S0 h7 u
假设我们想要抓取关于文本,Star的数量和Github回购页面的问题链接:
* P2 z7 Q4 q& ~- N' S2 I1 f 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) 执行结果为:1 X$ c, e+ Z! b) Z6 O2 T1 ?
4 S9 T) o) R! X: ~/ b9 u; t 保存模型
0 S; @8 e# u% k! \ 我们可以保存抓取的模型以便以后使用:5 }% [% b% ^% ?, y- K
# 指定保存的文件路径
scraper.save('stackoverflow')
# 调用方法:
scraper.load('stackoverflow') AutoScraper简单介绍就到这里了,如果你想使用更多的功能,详见官方主页了解。
: n! | g; F, s( E# z5 e 5 B q/ h: ~2 j