第一章 Python 爬取网站信息
前言
本文只做技术讨论,大家不要一直爬这个小网站,记得加上time.sleep(时间)
爬虫只能爬取用户能获取的信息
提示:以下是本篇文章正文内容,下面案例可供参考
一、爬虫是什么?
爬虫,即网络爬虫,大家可以理解为在网络上爬行的一只蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛,如果它遇到自己的猎物(所需要的资源),那么它就会将其抓取下来
二、使用步骤
1.引入库
import sys import time import os import requests import re # 正则表达式,进行文字匹配 from bs4 import BeautifulSoup # (网页解析,获取数据) import urllib.request, urllib.error # 制定URL,获取网页数据,urllib.request urllib.error import sqlite3
2.读取数据
import sys
import time
import os
import requests
import re # 正则表达式,进行文字匹配
from bs4 import BeautifulSoup # (网页解析,获取数据)
import urllib.request, urllib.error # 制定URL,获取网页数据,urllib.request urllib.error
import sqlite3
url = 'https://www.3gbizhi.com/tag/dongman/3.html'#自己增加format会吧,线性的,记得加sleep
headers = {
'user-agent': '自己的user-agent'}
response = requests.get(url=url, headers=headers)
html = response.text
print(html)
# html.encode('utf-8')
urls = re.findall('<img lazysrc="(.*?)" lazysrc2x=".*?" height="348px" alt=".*?" title=".*?" />', html)
filename = 'D:\二次元图片爬取\\'
print(urls)
if not os.path.exists(filename):
os.mkdir(filename)
for url in urls:
name = url.split('/')[-1]
response = requests.get(url, headers=headers)
# with open(filename+'小猫咪'+'.png',mode='wb') as f:
with open(filename + name, mode='wb') as f:
f.write(response.content)
同步爬取,不过不是高清的图片,只有点击进去才能得到高清图,这个时候我想用用selenium模拟浏览器操作,用click点击,然后抓取xpath,不过在观察后发现照片网址有规律,所以高清图片的获取就有了简单方法
高清图片获取代码:
import sys
import time
import os
import requests
import re # 正则表达式,进行文字匹配
from bs4 import BeautifulSoup # (网页解析,获取数据)
import urllib.request, urllib.error # 制定URL,获取网页数据,urllib.request urllib.error
import sqlite3
# url = 'https://www.3gbizhi.com/wallDM/4383.html'#自己增加format会吧,线性的,记得加sleep
k = int(input("请输入爬取页面数:"))
for i in range(0, k+1):
url = 'https://www.3gbizhi.com/wallDM/{}.html'.format(4808-i)
headers = {
'user-agent': '自己的ua'}
response = requests.get(url=url, headers=headers)
html = response.text
# html.encode('utf-8')
# urls = re.findall('<img lazysrc="(.*?)" lazysrc2x=".*?" height="348px" alt=".*?" title=".*?" />', html)
urls = re.findall('<img src="(.*?)" alt=".*?"></a>', html)
filename = 'D:\二次元图片高清\\'
print(urls)
time.sleep(0.1) #留点缓冲时间
if not os.path.exists(filename):
os.mkdir(filename)
if len(urls) != 0:
for url in urls:
name = url.split('/')[-1]
response = requests.get(url, headers=headers)
# with open(filename+'小猫咪'+'.png',mode='wb') as f:
with open(filename + name, mode='wb') as f:
f.write(response.content)
if i == k:
print("爬取结束了")
总结
以上就是今天要讲的内容,本文仅仅简单介绍了爬虫的使用,可以套模板使用,效果如下: