画师通每日榜单爬取
步骤
- 用selenium初始化webdriver驱动
- css寻址获得榜单所有图片的链接
- 循环遍历所有的链接并解析页面信息
- re正则表达式匹配链接
- 保存图片
导入工具箱
import re
import time
import requests
from selenium import webdriver
from bs4 import BeautifulSoup
初始化webdriver
#设置浏览器,executable_path为驱动存放的路径
driver = webdriver.Chrome(executable_path = 'F:\chromedriver\chromedriver.exe') # 设置引擎为Chrome
获得榜单所有图片的链接
在用selenium爬取信息时页面的部分信息可能会丢失,因此采用增加睡眠时间和自动化拖动滚动条的方法使得页面加载完全
#创建存放新链接的列表
newlinks = []
#触站每日排行榜
url = 'https://www.huashi6.com/rank'#一页50张
driver.get(url)
time.sleep(2)
#将滚动条移动到页面的底部获得页面所有信息
js="var q=document.documentElement.scrollTop=100000"
driver.execute_script(js)
time.sleep(2)
#获得链接
for i in range(1,51):
link = driver.find_element_by_css_selector('#app > div.p-rank-index > div.p-rank-list > a:nth-child({})'.format(i)).get_attribute('href')
newlinks.append(link)
#关闭浏览器
driver.quit()
编写自定义函数爬取页面并保存图片
def getHTMLText(url):
try:
headers = {"User-Agent":"Mozilla/5.0 "}
r = requests.get(url=url,headers=headers)
r.raise_for_status()
r.encoding = r.apparent_encoding
#返回页面的文本信息
news = r.text
#用BeautifulSoup解析页面信息
soup = BeautifulSoup(news,"html.parser")
#标题
title = soup.select('#app > div.p-work-detail > div.c-works-detail > div.works-panel > div.works-detail-left > div.describe > h1')[0].get_text()
#用正则表达式匹配出链接
pip = re.compile('img2.huashi6.com/images/resource.*?x')
newlink = pip.findall(news)[0]
#对链接进行预处理
link = [x for x in newlink.split('/')]
link[-1] = '2560x'
newurl = 'http://' + "/".join(link) + '/format/jpeg'
#访问保存图片的网页
r = requests.get(url=newurl,headers=headers)
#存储图片
f = open('D:\Pixiv\日榜\{}.jpg'.format(title),'wb')
f.write(r.content)
f.close()
print('第{}张存储完成'.format(count))
except:
return "产生异常1"
循环遍历所有链接
#开始爬取
count = 1
for link in newlinks:
getHTMLText(link)
count += 1
print('爬取完成')