简介 : e p8 L$ P C$ ]' s; \- F
AutoScraper 是使用 Python 实现的 Web 爬虫,兼容 Python 3,能快速且智能获取指定网站上的数据,这些数据可以是网页文本、URL 地址或者是其它 HTML 元素。另外,它还可以学习抓取规则并返回类似的元素。
6 E- t1 o- w7 }8 @ 下载安装
9 F% a6 `' o: f5 [7 b4 t* \ 项目的源码地址是:https://github.com/alirezamika/autoscraper & H; f1 n0 R& n( l& i u3 s3 p& [
兼容 Python 3。可使用以下方法进行安装:: |' l& w8 {- ?9 k
(1)从git获取安装 $ pip install git+https://github.com/alirezamika/autoscraper.git
- h9 L2 j' n! x, G (2)从PyPI获取安装 $ pip install autoscraper
/ n' @1 q' v _2 l (3)下载源码后进行安装 $ python setup.py install
9 N6 _5 D6 B/ z2 E( z6 Y5 g 简单使用 ; C7 z1 o2 g0 q" Z$ x5 Q- |
假设我们想在stackoverflow页面中获取所有相关的文章标题:
8 c s, j9 s/ _) f* | 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) 输出结果如下:
/ F7 T2 \4 s* W1 C. p. [: k M% 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?'
]抓取相似结果 ) D5 Y$ [$ E& U
当你还想获取stackoverflow上其他页面中所有相关的文章标题,则可以直接通过get_result_similar方法获取:
% z/ ^5 a9 ?. o1 R5 c2 K scraper.get_result_similar('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 两个页面的抓取结果为:
4 V- Y% J+ n) \
3 A- |. r& J& n, Q! H9 C0 \( q 抓取确切结果 0 ?% a5 A7 M# M A3 Z5 t" E
当你只想抓取某个确切的结果,可以使用get_result_exact方法,即从wanted_list中以完全相同的顺序检索数据:9 R* R$ {5 P- A
scraper.get_result_exact('https://stackoverflow.com/questions/606191/convert-bytes-to-a-string') 比如抓取页面中排第2的相关文章标题,执行结果:
f' M7 L7 w1 ?
8 f* D6 @: k3 c, Z2 e' H
自定义请求模块参数
2 S$ @% C4 |4 S# ~0 v* S$ ` 你还可以传递任何自定义请求模块参数。例如,你可能想使用代理或自定义头:
! ]% |$ O% ]' [1 L" E' ?: \2 Q 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))抓取多项信息
; N4 Q1 X7 W( Z4 Z! u 假设我们想要抓取关于文本,Star的数量和Github回购页面的问题链接:
8 R+ R! W1 c e+ S 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) 执行结果为:! ?6 n, G4 {& v5 i' Z T
9 y" G; U, D' j( ^- a& A 保存模型
' E! _$ _1 [2 T y7 B, p _( i- Z 我们可以保存抓取的模型以便以后使用:. i5 |( X: n* O9 X6 {/ k
# 指定保存的文件路径
scraper.save('stackoverflow')
# 调用方法:
scraper.load('stackoverflow') AutoScraper简单介绍就到这里了,如果你想使用更多的功能,详见官方主页了解。; g) M" U7 N+ [) t; a4 w/ h0 H) {
: p/ K& M. u# w( m