简介
/ X! c$ [/ B# K( b AutoScraper 是使用 Python 实现的 Web 爬虫,兼容 Python 3,能快速且智能获取指定网站上的数据,这些数据可以是网页文本、URL 地址或者是其它 HTML 元素。另外,它还可以学习抓取规则并返回类似的元素。
' c5 R! i8 H( @( Q/ g) ^1 a y+ m) k 下载安装
' }8 \& J1 x+ \/ ]& }# h 项目的源码地址是:https://github.com/alirezamika/autoscraper
/ o9 @3 J6 c/ q& L8 j7 m2 O8 L2 H, c 兼容 Python 3。可使用以下方法进行安装:1 o8 K# N9 F: f& @
(1)从git获取安装 $ pip install git+https://github.com/alirezamika/autoscraper.git 1 ^; l4 T2 T! Z9 z2 V. z1 T
(2)从PyPI获取安装 $ pip install autoscraper7 `' P* h/ L" [2 [# B* l. C2 S
(3)下载源码后进行安装 $ python setup.py install* F4 a4 R0 ]& v9 F; O
简单使用 5 t# s$ X$ N8 ^& ?7 [4 }0 W8 U4 K" C
假设我们想在stackoverflow页面中获取所有相关的文章标题:1 E- u5 ]# W1 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) 输出结果如下:: U& k7 s4 P9 D
[
'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?'
]抓取相似结果 : L0 {+ g- f; l) J; c. s# j
当你还想获取stackoverflow上其他页面中所有相关的文章标题,则可以直接通过get_result_similar方法获取:* d2 e- z- ^5 `. L
scraper.get_result_similar('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 两个页面的抓取结果为:4 b# L9 j7 M7 D- Q/ w" C
6 O4 _7 l7 H, t) Y5 B9 t
抓取确切结果
! h* Y4 o4 Y+ s5 K# b# p" B+ L 当你只想抓取某个确切的结果,可以使用get_result_exact方法,即从wanted_list中以完全相同的顺序检索数据:0 F% } ~! @) s
scraper.get_result_exact('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 比如抓取页面中排第2的相关文章标题,执行结果:8 K7 z3 _# A1 y# h$ k# x# i* R
9 x4 U5 Q' M: t; O6 U
自定义请求模块参数 1 R4 Z* r# e0 i$ M. v
你还可以传递任何自定义请求模块参数。例如,你可能想使用代理或自定义头:& p8 a1 ?% F2 I
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))抓取多项信息
* H; b# j1 n) ^+ Y 假设我们想要抓取关于文本,Star的数量和Github回购页面的问题链接:& S( S/ w4 t0 j8 y
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) 执行结果为:
$ o9 p) u+ ~9 N# N! T: v
- z e2 F3 h. d2 b1 {- U
保存模型
5 A2 z) M/ O- n5 \% u7 D6 l$ U4 p2 L, i 我们可以保存抓取的模型以便以后使用:/ \8 K8 k" d' h# A' G$ j7 c' g" V: U
# 指定保存的文件路径
scraper.save('stackoverflow')
# 调用方法:
scraper.load('stackoverflow') AutoScraper简单介绍就到这里了,如果你想使用更多的功能,详见官方主页了解。
! e8 @4 q, T& [+ K* R5 o& H
; {% V! ?) t Z