简介 & X6 l* g$ L5 z' i' U7 j1 Q
AutoScraper 是使用 Python 实现的 Web 爬虫,兼容 Python 3,能快速且智能获取指定网站上的数据,这些数据可以是网页文本、URL 地址或者是其它 HTML 元素。另外,它还可以学习抓取规则并返回类似的元素。' W, t8 i2 W$ N' ^* d/ v! R6 ?! T7 g
下载安装 3 a* w, h* D$ N A2 z1 g
项目的源码地址是:https://github.com/alirezamika/autoscraper 3 Q8 k$ }) y# C9 Q% U! b
兼容 Python 3。可使用以下方法进行安装:) i+ h r0 i- _3 K( v" z+ L* G
(1)从git获取安装 $ pip install git+https://github.com/alirezamika/autoscraper.git
7 Q. m8 j! U4 A5 [) z8 h' F. z (2)从PyPI获取安装 $ pip install autoscraper. M1 m7 V) f! s
(3)下载源码后进行安装 $ python setup.py install
8 N5 l# X8 o8 m; {2 F 简单使用
- n; U4 h" I: I: b 假设我们想在stackoverflow页面中获取所有相关的文章标题:& _/ _4 I! k- Q1 Y4 @0 K- I. b
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# B/ d1 [! o* ~ O% Y' ?' h8 q2 P
[
'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 \4 P3 V7 p5 M; a% f% U+ Z' H
当你还想获取stackoverflow上其他页面中所有相关的文章标题,则可以直接通过get_result_similar方法获取:
* O4 `8 ^+ R |& b! n9 r scraper.get_result_similar('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 两个页面的抓取结果为:
# Z1 \) I8 C1 w; k* Q2 w+ L: o6 l
7 E7 b) D% W$ Z @: M& L/ u# ]
抓取确切结果
8 ]8 h3 Q5 |$ s1 i1 a 当你只想抓取某个确切的结果,可以使用get_result_exact方法,即从wanted_list中以完全相同的顺序检索数据:
4 F. n- V) ^; Q, E6 x# U8 j scraper.get_result_exact('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 比如抓取页面中排第2的相关文章标题,执行结果:
; R0 G2 a+ X& J: Z
0 n: E9 ]. ^9 l) K0 j4 J 自定义请求模块参数 9 ]) e9 W3 @2 V6 O8 e+ R4 G
你还可以传递任何自定义请求模块参数。例如,你可能想使用代理或自定义头:
E% V& O A) ? @& u2 { 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))抓取多项信息
' t! A9 J0 N0 ]; b' v2 Q 假设我们想要抓取关于文本,Star的数量和Github回购页面的问题链接:* F) j: {1 v9 f" J% o) M
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) 执行结果为:4 x9 r5 W# t6 q" u" o6 a
/ z* X+ |+ F& `4 d K7 j1 |
保存模型
4 M, P. h$ {6 l' B 我们可以保存抓取的模型以便以后使用:& k. S# D& G' |8 a/ a. \- t5 `
# 指定保存的文件路径
scraper.save('stackoverflow')
# 调用方法:
scraper.load('stackoverflow') AutoScraper简单介绍就到这里了,如果你想使用更多的功能,详见官方主页了解。 C' x7 Z, o1 T$ C7 F& w
2 k" V) x$ _ b* q' D