首页 运维 网络学院 查看内容

Python网络爬虫1 – 简单的Http请求

2016-8-22 11:00 1354 0

摘要: 最近这段时间会有需要写一个网络爬虫。会在这里将实现网络爬虫的经验记录下来。 爬虫什么的,只是一个名字罢了。简单地说,也都是从http请求开始的。 Python实现http请求主要依赖的是urllib.request模块。例如发送Ht ...

最近这段时间会有需要写一个网络爬虫。会在这里将实现网络爬虫的经验记录下来。

爬虫什么的,只是一个名字罢了。简单地说,也都是从http请求开始的。

Python实现http请求主要依赖的是urllib.request模块。例如发送Http请求:

就是这么简单。

通常,在命令行打印出来的是要抓取的网页的源代码。想从中过滤出来需要的信息可以再次进行匹配和筛选。比如使用正则式匹配获取title和body中的内容:

对于一些采集程序来说做到这里就够了。如果我们要的是网页的内容而非网页的html,则需要使用比正则表达式更强大的工具。在下一节会用一个实例介绍相关的内容。

附上完整的程序:

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!python
# encoding: utf-8
import re
from urllib import request
from urllib import parse
 
 
def get(url):
    response = request.urlopen(url)
    content = ""
    if response:
        content = response.read().decode("utf8")
        response.close()
    return content
 
 
def post(url, **paras):
    param = parse.urlencode(paras).encode("utf8")
    req = request.Request(url, param)
    response = request.urlopen(req)
    content = ""
    if response:
        content = response.read().decode("utf8")
        response.close()
    return content
 
 
def get_target(pattern, content):
    m = re.search(pattern, content)
    target = ""
    if m:
        target = m.group(0)
    return target
 
 
def main():
    url = 'http://www.zhyea.com/2016/07/17/memory-analyzer-all.html'
    content = get(url)
    title = get_target(r"<title>.*<\title>", content)
    body = get_target(r"<body[\w|\W]*<body>", content)
 
 
if __name__ == "__main__":
    main()
声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系 [邮箱地址] 删除

路过

雷人

握手

鲜花
1

鸡蛋

刚表态过的朋友 (1 人)

  • 鸡蛋

    匿名

最新评论

返回顶部