温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python实现网络爬虫的案例

发布时间:2020-10-22 11:15:58 来源:亿速云 阅读:199 作者:小新 栏目:编程语言

小编给大家分享一下python实现网络爬虫的案例,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

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

python实现网络爬虫的方法:

第一步:爬取

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

编写代码

[root@localhost demo]# touch demo.py
[root@localhost demo]# vim demo.py
#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) )
[root@localhost demo]# python3 demo.py

python实现网络爬虫的案例

第二步:分析

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

编写代码

[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)        #打印输出
[root@localhost demo]# python3 demo1.py

python实现网络爬虫的案例

看完了这篇文章,相信你对python实现网络爬虫的案例有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI