python爬虫学习
前言
提示:这里可以添加本文要记录的大概内容:
写的第一个爬虫程序,不足之处还请大佬斧正。
提示:以下是本篇文章正文内容,下面案例可供参考
一、python爬虫
利用python中的数据库进行网页信息的提取
二、使用步骤
1.引入库
代码如下(示例):
import urllib.request
import xlwt
import re
from bs4 import BeautifulSoup
2.解析网页函数
代码如下(示例):
def jiexi(url):#解析网页
head={
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.39"
}#冲破障碍,直达网站
request = urllib.request.Request(url,headers=head)
html=""#创建一个空字符串进行接收网页信息
try:#检查是否有报错
response=urllib.request.urlopen(request)
html=response.read().decode("utf-8")
print(html)
except urllib.error.URError as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
return html
该处使用的url网络请求的数据。
3.获取数据函数
代码如下(示例):
def getdata(baseural):#获取网站数据,即源码解析后的数据提取
datalist=[]
for i in range(1,51):#1~50页的网页
url=baseural+str(i)#网页后面进行加减,从而进行模拟翻页
# print(url)
html=jiexi(url)
soup=BeautifulSoup(html,"html.parser")#用的是