python爬虫——https请求

本文介绍了Python爬虫在处理HTTPS请求时如何忽略SSL证书,深入探讨了相关技术和实践。

python爬虫——https请求

from urllib.request import Request,urlopen
from fake_useragent import UserAgent
import ssl
url = "https://www.12306.cn/index/"
headers = {
   
   
    "User-Agent":UserAgent().random
}
request = Request(url
使用Python编写一个简单的网页小说下载器,可借助requests库和BeautifulSoup库。requests库用于发送HTTP请求获取网页内容,BeautifulSoup库用于解析HTML内容,从中提取所需的小说文本信息。 以下是一个简单示例代码,假设小说页面结构较为简单,小说章节链接可以直接获取,且章节内容在特定的HTML标签内: ```python import requests from bs4 import BeautifulSoup # 定义函数,获取小说章节页面内容 def get_chapter_content(url): try: response = requests.get(url) response.raise_for_status() response.encoding = response.apparent_encoding soup = BeautifulSoup(response.text, 'html.parser') # 假设小说内容在一个特定的<div>标签中,这里需要根据实际网页结构修改 content_div = soup.find('div', class_='content') if content_div: return content_div.get_text() return None except requests.RequestException as e: print(f"请求出错: {e}") return None # 定义函数,下载小说 def download_novel(novel_url, save_path): try: response = requests.get(novel_url) response.raise_for_status() response.encoding = response.apparent_encoding soup = BeautifulSoup(response.text, 'html.parser') # 假设章节链接在一个特定的<ul>标签中的<a>标签里,需要根据实际网页结构修改 chapter_links = soup.find_all('a', class_='chapter-link') with open(save_path, 'w', encoding='utf-8') as file: for link in chapter_links: chapter_url = link['href'] chapter_title = link.get_text() file.write(f"{chapter_title}\n") chapter_content = get_chapter_content(chapter_url) if chapter_content: file.write(chapter_content) file.write("\n\n") except requests.RequestException as e: print(f"请求出错: {e}") # 示例使用 novel_url = "https://example.com/novel" # 替换为实际的小说目录页URL save_path = "novel.txt" # 保存的文件路径 download_novel(novel_url, save_path) ``` 上述代码仅是一个基础示例,实际应用中,不同小说网站的HTML结构差异很大,需要根据具体网站的结构调整代码,找到正确的章节链接和内容所在的HTML标签。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值