python如何实现网络爬虫


本文摘自php中文网,作者coldplay.xixi,侵删。

python实现网络爬虫的方法:1、使用request库中的get方法,请求url的网页内容;2、【find()】和【find_all()】方法可以遍历这个html文件,提取指定信息。

python实现网络爬虫的方法:

第一步:爬取

使用request库中的get方法,请求url的网页内容

编写代码

1

2

[root@localhost demo]# touch demo.py

[root@localhost demo]# vim demo.py

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

#web爬虫学习 -- 分析

#获取页面信息

  

#输入:url

#处理:request库函数获取页面信息,并将网页内容转换成为人能看懂的编码格式

#输出:爬取到的内容

  

import requests

  

def getHTMLText(url):

    try:

        r = requests.get( url, timeout=30 )

        r.raise_for_status()    #如果状态码不是200,产生异常

        r.encoding = 'utf-8'    #字符编码格式改成 utf-8

        return r.text

    except:

        #异常处理

        return " error "

  

url = "http://www.baidu.com"

print( getHTMLText(url) )

1

[root@localhost demo]# python3 demo.py

6387e49f8185b7d812adb77c9e7f119.png

第二步:分析

使用bs4库中BeautifulSoup类,生成一个对象。find()和find_all()方法可以遍历这个html文件,提取指定信息。

编写代码

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

[root@localhost demo]# touch demo1.py

[root@localhost demo]# vim demo1.py

#web爬虫学习 -- 分析

#获取页面信息

  

#输入:url

#处理:request库获取页面信息,并从爬取到的内容中提取关键信息

#输出:打印输出提取到的关键信息

  

import requests

from bs4 import BeautifulSoup

import re

  

def getHTMLText(url):

    try:

        r = requests.get( url, timeout=30 )

        r.raise_for_status()    #如果状态码不是200,产生异常

        r.encoding = 'utf-8'    #字符编码格式改成 utf-8

        return r.text

    except:

        #异常处理

        return " error "

  

def findHTMLText(text):

    soup = BeautifulSoup( text, "html.parser" )    #返回BeautifulSoup对象

    return soup.find_all(string=re.compile( '百度' )) #结合正则表达式,实现字符串片段匹配

  

url = "http://www.baidu.com"

text = getHTMLText(url)        #获取html文本内容

res = findHTMLText(text)    #匹配结果

  

print(res)        #打印输出

1

[root@localhost demo]# python3 demo1.py

4c09a57891201d0e5fb214a6438b0ff.png

相关免费学习推荐:python视频教程

以上就是python如何实现网络爬虫的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python使用arrow库处理时间数据的示例详解

Python学习笔记之open()函数打开文件路径报错问题

Python生成脚本--实现数据库更新

Python逻辑运算符怎么理解

Python怎么批量读取txt文件为dataframe格式

Python:中input()与raw_input()的详解

Python源代码被解释器转换后的格式为什么

Python print用法详解

Python中的seed()方法怎么用

Python怎么把string变为hex

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...