|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
仅适用于可访问的页面,且仅保存第一页,主要是练手,顺便保存一下速查资料
有需要的萌新小伙伴可以自行更改用户名密码及网址
from urllib.parse import urljoin
from pathlib import Path
import requests
from fake_useragent import UserAgent, errors
from bs4 import BeautifulSoup
# 获取
def get_info(session: requests.Session, url):
response = session.get(url)
return response
# 保存
def save_info(session: requests.Session, response: requests.get):
soup = BeautifulSoup(response.content, 'lxml')
p = Path('.')
path_name = soup.find('title').text
p.joinpath(path_name).mkdir(parents=True, exist_ok=True)
# 图片保存
img_info = soup.find_all('img')
for img in img_info:
try:
img_url = urljoin('https://fishc.com.cn/', img['src'])
img_response = session.get(img_url)
img_name = img['src'].split('/')[-1].split('?')[0].strip()
img['src'] = f'./{path_name}'
with open(f'{path_name}/{img_name}', 'wb') as file:
print(f'正在保存图片->{img_name}')
file.write(img_response.content)
except Exception as e:
print(f'图片保存错误: {e}')
# css保存
css_info = soup.find_all('link', {'rel': 'stylesheet'})
for css in css_info:
try:
css_url = urljoin('https://fishc.com.cn/', css['href'])
css_response = session.get(css_url)
css_name = css['href'].split('/')[-1].split('?')[0].strip()
css['href'] = f'./{path_name}'
with open(f'{path_name}/{css_name}', 'wb') as file:
print(f'正在保存css->{css_name}')
file.write(css_response.content)
except Exception as e:
print(f'css保存错误: {e}')
# html保存
with open(f'{p}/{path_name}.html', 'wb') as file:
file.write(response.content)
print(f'网页保存完毕')
if __name__ == '__main__':
try:
url = 'https://fishc.com.cn/thread-183975-1-1.html' #可替换url
url_login = 'https://fishc.com.cn/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1'
session = requests.Session()
header = {'User-Agent': UserAgent().random}
session.headers = header
login_info = {'username': 'yourname',
'password': 'yourpassword'}
session.post(url_login, data=login_info)
response = get_info(session, url)
save_info(session, response)
except errors.FakeUserAgentError as e:
print(f'FakeUserAgentError: {e}')
except requests.exceptions.RequestException as e:
print(f'RequestException: {e}')
|
|