python爬虫爬取数据步骤:
1,获得数据。2,整理数据,检索出自己需要的数据。3,保存到本地
静态网页的爬取:
1,获得数据
import urllib.request
url = "https://www.baidu.com/" # 要爬取网页的网址
head = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'
} # 给服务器的数据,可用来伪装
req = urllib.request.Request(url=url, headers=head) # 封装一个对象
response = urllib.request.urlopen(req) # 打开该对象
html = response.read().decode("utf-8") # 读取获得的数据,解码
print(html) # 打印,可得到html文件
2,整理数据,检索出自己需要的数据
from bs4 import BeautifulSoup # 导入所需的库
import re # 正则表达式的库
html = BeautifulSoup(html, "html.parser") # 将获得的前面获得html文档用树形结构存储
find = re.compile(r'"pure_title": "(.*?)"') # 定义正则表达式
html = re.findall(find, str(html)) # 查找内容,用正则表达式则需将html转化为str类型
# 这里不一定要用正则表达式匹配内容,由于是BeautifulSoup类型,所以也可以用其他方法匹配数据
此时再次打印html,可获得以下数据
3,保存到本地
file = open("t.txt", "w") # 写入的方式打开一个文件
for i in html:
file.writelines(i+'\n') # 我这里选择按行写入
file.close() # 关闭文件
# 也可以在python中导入数据库的模块,将数据保存在数据库中