python实现网络爬虫代码_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

第二步:分析

使用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

相关推荐
waterHBO39 分钟前
python 爬虫 selenium 笔记
爬虫·python·selenium
编程零零七2 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
2401_858286113 小时前
52.【C语言】 字符函数和字符串函数(strcat函数)
c语言·开发语言
铁松溜达py3 小时前
编译器/工具链环境:GCC vs LLVM/Clang,MSVCRT vs UCRT
开发语言·网络
everyStudy3 小时前
JavaScript如何判断输入的是空格
开发语言·javascript·ecmascript
AIAdvocate4 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼4 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
C-SDN花园GGbond4 小时前
【探索数据结构与算法】插入排序:原理、实现与分析(图文详解)
c语言·开发语言·数据结构·排序算法
迷迭所归处5 小时前
C++ —— 关于vector
开发语言·c++·算法
架构文摘JGWZ6 小时前
Java 23 的12 个新特性!!
java·开发语言·学习