网络爬虫(附带实例)

2023-12-14 14:37:29

一、主要目的:

初步熟悉在Python开发环境中对网络爬虫执行流程:获取网页源码、从源码中提取相关信息以及进行数据存储,每个环节提供的技术支撑。通过查阅相关说明文档掌握python内置的urllib.request模块,Beautiful Soup库的基本使用方法。基于实际Web环境内容,完成网络爬虫的示例编写。

二、主要内容:

1、网络爬虫执行流程的分步实践
(1)获取网页源码

通过Python 内置的urllib.request模块获取网页的字节码,通过对字节码的解码获取网页的源码字符串。

使用chardet库判断网页编码方式,并不是所有网页都采用utf-8编码方式。

(2)从源码中提取信息

熟悉Beautiful Soup库,运用该库从网页抓取数据,它可以方便地提取出HTML或XML标签中的内容。

编写一个示例,运用Beautiful Soup库从源码中提取信息,通过解析文档为用户提供需要抓取的数据。

  1. 数据存储
??? ① 保存到csv文件

python自带的csv模块可以处理csv文件,编写数据存储的示例

②保存到数据库

尝试使用pythoon支持的原生数据库sqlite3数据库,编写数据存储的示例。

2、编写网络爬虫
(1)手工打造网络爬虫

第一步:引入相关包

第二步:获取网页源码,生成soup对象

第三步:解析数据

第四步:获取下一页链接

第五步:组织代码结构开始爬行

import requests

from bs4 import BeautifulSoup

import bs4

def getHTMLText(url):

??? try:

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

??????? r.raise_for_status()

??????? r.encoding=r.apparent_encoding

??????? return r.text

??? except:

??????? return""

def fillUnivList(ulist,html):

??? soup=BeautifulSoup(html,'html.parser')

??? for tr in soup.find('tbody').children:

??????? if isinstance(tr,bs4.element.Tag):

??????????? tds=tr('td')

??????????? ulist.append([tds[0].string,tds[1].string,tds[2].string,tds[3].string])

???????????

def printUnivList(ulist,num):

??? print("{:^10}\t{:^14}\t{:^10}\t{:^10}".format("排名",'院校','所在地','类型',chr(12288)))

??? for i in range(num):

??????? u=ulist[i]

??????? print('{:^10}\t{:^10}\t{:^10}\t{:^10}'.format(u[0],u[1],u[2],u[3]),chr(12288))

def main():

??? uinfo=[]

??? url="http://www.dxpmw.com/"

??? html=getHTMLText(url)

??? fillUnivList(uinfo,html)

??? printUnivList(uinfo,6)#20 univs

main()

  1. 基于Scrapy 抓取框架,打造网络爬虫[附选]

三、源码附件:

1(1)

from urllib import request

file=request.urlopen('https://s.taobao.com/')

html=file.read()

print(html)

html=html.decode("utf-8")

print(html)

(2)

from urllib import request

import chardet

file=request.urlopen('https://s.taobao.com/')

html=file.read()

charset=chardet.detect(html)

print(charset)

2

import urllib.request

from bs4 import BeautifulSoup

response=urllib.request.urlopen("https://s.taobao.com/")

html=BeautifulSoup(response.read().decode(),"lxml")

print(type(html))

(1)import csv

with open('data.csv','w') as csvfile:

??? writer = csv.writer(csvfile,delimiter=' ')

??? writer.writerow(['id','name','age'])

??? writer.writerow(['10001','Mike',20])

??? writer.writerow(['10002','Bob',22])

writer.writerow(['10003','Jordan',21])

(2)import requests

import re

words={}

def add_word(word_line):

??? global words

??? #用词性作为分隔符分隔字符串

??? result1=re.split('[a-z]+\.',word_line)

??? pattern=re.compile('[a-z]+\.')???

??? #搜索所有词性

??? result2=pattern.findall(word_line)

??? #得到单词

??? word=result1[0].strip()

??? #保存单词的解释,以词性作为key,解释作为Value

??? meanings={}

??? for i in range(0,len(result2)):

??????? key=result2[i].strip()

??????? value=result1[i+1].strip()

??????? meanings[key]=value

??? words[word]=meanings

r=requests.get('https://www.eol.cn/html/en/cetwords/cet4.shtml')

html=r.content

html_doc=str(html,'utf-8')

from bs4 import BeautifulSoup

soup=BeautifulSoup(html_doc,'lxml')

tags=soup.find_all(attrs={'class':'wordL fl'})

for tag in tags:

??? p_list=tag.select('p')

??? for p in p_list:

??????? add_word(p.text)

print(words)#得到一长串数据,暂不解析

print('单词抓取完毕')

####生成本地词库######

import sqlite3

import os

db_path='d://dict.sqlite'#设置数据库路径

if os.path.exists(db_path):#如果数据库存在

??? os.remove(db_path)#删除存在的数据库

conn=sqlite3.connect(db_path)

c=conn.cursor()

c.execute('''create table words

??? (id int primary key not null,

??? word varchar(30) not null,

??? type varchar(10) not null,

??? meanings text not null);''')

c.execute('create index word_index on words(word)')

conn.commit()

conn.close()

print('创建数据库成功')#创建完成一个空数据库名dict,表words

#将抓取到的数据转存到dict中

conn=sqlite3.connect(db_path)

c=conn.cursor()?

i=1

for word in words:#拆分从网页抓取到的数据

??? value=words[word]

??? for type in value:

??????? meanings=value[type]

??????? sql =f'insert into words(id,word,type,meanings)\

??????? values({i},"{word}","{type}","{meanings}")';

??????? c.execute(sql)

??????? i+=1

??? conn.commit()

conn.close()

print('电子词典数据库已生成')

四、心得

? 在本次实验中,我学习了如何使用Python进行网络爬虫,以及如何处理和存储爬取的数据。我主要使用了requests库来发送HTTP请求,BeautifulSoup库来解析HTML文档,以及csv和sqlite3模块来存储和管理数据。

? 我首先通过requests库向目标网页发送了一个GET请求,然后用BeautifulSoup库解析得到的HTML文档。在解析的过程中,我学会了如何使用find_all和select方法来查找特定的HTML标签和属性,以及如何使用正则表达式来处理复杂的文本。

? 在数据存储方面,我首先尝试了使用csv模块将数据保存为CSV文件。然后我学习了如何使用sqlite3模块来创建SQLite数据库,以及如何通过SQL语句来插入和查询数据。

? 通过本次实验,我深入理解了网络爬虫的工作原理,以及如何使用Python来实现网络爬虫。此外,我也学会了如何处理和存储爬取的数据,这对我日后在数据分析和处理方面的工作会有很大的帮助。

文章来源:https://blog.csdn.net/xixixi7777/article/details/134979955
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。