1.需要导入库
from bs4 import BeautifulSoup #网页解析,获取数据
import re #正则表达式,文字匹配
import urllib.request,urllib.error #制定URL,获取网页数据
import xlwt #进行excel操作
import sqlite3 #进行数据库操作
2.步骤
(1)爬取网页
(2)解析数据
(3)保存数据
(1)爬取网页
得到一个指定URL的网页内容
def askURL(url):
head={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64"
} #用户代理,模拟浏览器头部信息
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.URLError as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
return html
head内容获取:
(1)进入网页,按f12
(2)点击网络
(3)ctrl+R或点击刷新,然后点击小红点暂停
(4)找到第一个文件