鱼C论坛

 找回密码
 立即注册
查看: 1753|回复: 2

[作品展示] 学习爬虫初期练习,保存鱼c论坛网页

[复制链接]
发表于 2023-11-23 17:46:38 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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}')

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-11-23 17:47:58 | 显示全部楼层
你的代码看起来已经很不错了,可以实现保存鱼C论坛网页的功能。不过有一些地方需要修改:

1. 导入的模块错误,正确的模块名是`from fake_useragent import UserAgent, errors`,请注意大小写。
2. `response` 是一个 `requests.Response` 对象,而不是 `requests.get` 对象,因此在 `save_info` 函数中将其参数改为 `response: requests.Response`。
3. 在获取图片和 CSS 的 URL 时,不能直接使用 `urljoin` 函数,因为 `img` 和 `css` 是 BeautifulSoup 返回的 Tag 对象,需要使用 `.get('src')` 和 `.get('href')` 方法来获取其属性值。
4. 在保存图片和 CSS 时,要使用正确的文件名,可以使用 `os.path.basename` 函数来获取 URL 中的文件名部分。

这里是修改后的代码:
  1. from urllib.parse import urljoin
  2. import os
  3. import requests
  4. from fake_useragent import UserAgent, errors
  5. from bs4 import BeautifulSoup
  6. # 获取
  7. def get_info(session: requests.Session, url):
  8.     response = session.get(url)
  9.     return response
  10. # 保存
  11. def save_info(session: requests.Session, response: requests.Response):
  12.     soup = BeautifulSoup(response.content, 'lxml')
  13.     title = soup.find('title').text
  14.     path_name = title.strip()
  15.     os.makedirs(path_name, exist_ok=True)
  16.     # 图片保存
  17.     img_info = soup.find_all('img')
  18.     for img in img_info:
  19.         try:
  20.             img_url = urljoin(response.url, img.get('src'))
  21.             img_response = session.get(img_url)
  22.             img_name = os.path.basename(img_url)
  23.             with open(f'{path_name}/{img_name}', 'wb') as file:
  24.                 print(f'正在保存图片->{img_name}')
  25.                 file.write(img_response.content)
  26.         except Exception as e:
  27.             print(f'图片保存错误: {e}')
  28.     # css保存
  29.     css_info = soup.find_all('link', {'rel': 'stylesheet'})
  30.     for css in css_info:
  31.         try:
  32.             css_url = urljoin(response.url, css.get('href'))
  33.             css_response = session.get(css_url)
  34.             css_name = os.path.basename(css_url)
  35.             with open(f'{path_name}/{css_name}', 'wb') as file:
  36.                 print(f'正在保存css->{css_name}')
  37.                 file.write(css_response.content)
  38.         except Exception as e:
  39.             print(f'css保存错误: {e}')
  40.     # html保存
  41.     with open(f'{path_name}.html', 'wb') as file:
  42.         file.write(response.content)
  43.         print(f'网页保存完毕')
  44. if __name__ == '__main__':
  45.     try:
  46.         url = 'https://fishc.com.cn/thread-183975-1-1.html'
  47.         url_login = 'https://fishc.com.cn/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1'
  48.         session = requests.Session()
  49.         header = {'User-Agent': UserAgent().random}
  50.         session.headers = header
  51.         login_info = {'username': 'yourname',
  52.                       'password': 'yourpassword'}
  53.         session.post(url_login, data=login_info)
  54.         response = get_info(session, url)
  55.         save_info(session, response)
  56.     except errors.FakeUserAgentError as e:
  57.         print(f'FakeUserAgentError: {e}')
  58.     except requests.exceptions.RequestException as e:
  59.         print(f'RequestException: {e}')
复制代码
以上代码进行了修改,你可以根据自己的需要进一步调整和扩展。希望能对你有所帮助!
以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。

点评

ai果然不是那么智能  发表于 2023-11-23 21:24
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-24 08:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表