代码拉取完成,页面将自动刷新
# -*- coding: utf-8 -*-
# 031904138-王绮雯
# 爬取http://www.weather.com.cn/
# 8页138张图片(18*7+12=138)
import sqlite3
from urllib import request
import pandas as pd
from bs4 import BeautifulSoup, UnicodeDammit
import urllib.request
import requests
import re
# 使用urllib.request爬取网页
def getHTMLText(url):
try:
headers = {
"user-agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36"
}
req = urllib.request.Request(url=url,headers=headers)
data = urllib.request.urlopen(req)
data = data.read()
dammit = UnicodeDammit(data, ["utf-8", "gbk"])
data=dammit.unicode_markup
return data
except Exception as err:
print(err)
def parsePage(html,num): # num表示每页爬取的商品数量
list=[]
try:
soup = BeautifulSoup(html, 'html.parser')
imgs = soup.select('img')
imgs = str(imgs)
p_picture = re.compile('src="(.*?)"') #观察html文件内容后提取出关键字
pictures = re.findall(p_picture, imgs) #查找图片链接
for i in range(num): #按照指定数量得到列表
list.append(pictures[i])
return list
except:
return ""
# 输出图片链接列表
def printGoodsList(list):
tply="{0:^4}\t{1:^30}"
print(tply.format("序号","图片链接",chr(12288)))
count=1
for img in list:
print(tply.format(count,img,chr(12288)))
count = count + 1
#将每张图片写到本地
def save2file(img_url_list,path):
i=1
for img in img_url_list:
img_url = img
new_path = path + str(i) + ".jpg"
urllib.request.urlretrieve(img_url, new_path) #定义存取本地图片路径
i += 1
# 用于找到图片数量足够多的页面
def pagelinks(html):
soup = BeautifulSoup(html, 'html.parser')
link = soup.select('a') # 找到页面链接
p_link = re.compile('href="(.*?)"')
link = str(link)
links = re.findall(p_link, link)
pagelinks = [] # 找到图片数量足够的页面链接
num = 0
for i in range(len(links)):
if (num <= 10):
try:
html = getHTMLText(links[i])
soup = BeautifulSoup(html, 'html.parser')
imgs = soup.select('img')
p_picture = re.compile('src="(.*?)"') # 观察html文件内容后提取出关键字
imgs = str(imgs)
# print(imgs)
picture = re.findall(p_picture, imgs)
if (len(picture) >= 20):
pagelinks.append(links[i])
num += 1
except:
pass
return pagelinks
if __name__ == "__main__":
url = 'http://www.weather.com.cn/'
picture_list = [] #用于记录得到的图片链接
html = getHTMLText(url)
pagelink = pagelinks(html) # 找到其他页面跳转链接
page = 8 # 学号031904138 爬取页数为8,图片数量为138
for i in range(page): #138=7*18+1*12 最后一页爬取12项
url = pagelink[i]
html = getHTMLText(url) #爬取指定网页
if(i==page-1):
list = parsePage(html,12) # 解析网页提取需要的数据,最后一页提取12项
else:
list = parsePage(html, 18) # 解析网页提取需要的数据,提取前18项
picture_list.extend(list)
printGoodsList(picture_list) # 打印得到的数据
path = r"D:/wqwDownload/PyCharm Community Edition 2021.2.2/PycharmProjects/wqwcodes/爬虫实践课/第三次作业/picture/" #图片保存路径
save2file(picture_list,path) #将图片保存到本地文件
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。