简介
! \/ A% u* N( o. |1 m- x AutoScraper 是使用 Python 实现的 Web 爬虫,兼容 Python 3,能快速且智能获取指定网站上的数据,这些数据可以是网页文本、URL 地址或者是其它 HTML 元素。另外,它还可以学习抓取规则并返回类似的元素。& I' ^: I; W- ~3 O! k+ v8 w
下载安装 & N3 q0 t" ^: U5 ~1 \2 n- ?
项目的源码地址是:https://github.com/alirezamika/autoscraper
! o+ j4 ?" [( A) _8 B/ j 兼容 Python 3。可使用以下方法进行安装:. u1 I+ N0 h; `1 Y- F
(1)从git获取安装 $ pip install git+https://github.com/alirezamika/autoscraper.git
5 J: s j+ K( e. F/ o (2)从PyPI获取安装 $ pip install autoscraper" e# n' f% E z3 H5 g9 t
(3)下载源码后进行安装 $ python setup.py install
" Y) R0 k4 _9 Z4 B2 N- E) W 简单使用 / R0 `2 b! G, [
假设我们想在stackoverflow页面中获取所有相关的文章标题:) Z9 W; [6 E6 `2 B5 B8 [* t& w
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) 输出结果如下:9 G' p3 {2 ?4 f* d# V* R
[
'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?'
]抓取相似结果
1 v; e u& U+ U, J6 u4 M- Q# Q! Y 当你还想获取stackoverflow上其他页面中所有相关的文章标题,则可以直接通过get_result_similar方法获取:
2 N. k/ Z1 E6 Q9 Y9 I+ k1 p scraper.get_result_similar('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 两个页面的抓取结果为:
! A2 r! }- H+ q( N" Z9 f
! _/ w2 f, \% V3 \5 S 抓取确切结果 $ n& @9 P/ s& W& O: M1 f; c& K
当你只想抓取某个确切的结果,可以使用get_result_exact方法,即从wanted_list中以完全相同的顺序检索数据:: j1 s+ q" [- x; y; [, \
scraper.get_result_exact('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 比如抓取页面中排第2的相关文章标题,执行结果:
+ J3 x# Q4 e2 V5 `
- A1 X& Q7 J$ u) r; E8 G 自定义请求模块参数
# X+ f; f* Y/ _/ E5 Q 你还可以传递任何自定义请求模块参数。例如,你可能想使用代理或自定义头:
+ D7 n9 {4 ?' ^) p6 G, ?' C Z$ h 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))抓取多项信息
) @1 t- z7 s8 Q9 Q) V 假设我们想要抓取关于文本,Star的数量和Github回购页面的问题链接:
! q5 E8 P; S; ~; V 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) 执行结果为:
7 J: f9 ^4 W8 T) \$ _
0 w/ p4 L1 d( G- U& w( g 保存模型
4 l5 Y/ z- W; V* P, ]0 a9 ^ 我们可以保存抓取的模型以便以后使用:! i" Y5 g' v: f: K& o3 V( I
# 指定保存的文件路径
scraper.save('stackoverflow')
# 调用方法:
scraper.load('stackoverflow') AutoScraper简单介绍就到这里了,如果你想使用更多的功能,详见官方主页了解。
- j3 Q& e. ]8 H# K
1 t" n0 S) ~0 X! C1 B3 @" R4 `/ Q