下面以某小说网站为例:
import re import time import requests from bs4 import BeautifulSoup from testCase.testReptile.Log import log # 定义请求参数 headers = {‘User-Agent‘:‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36‘} # 定义请求IP url = ‘--网址--‘ # 执行请求 get_re = requests.get(url=url, headers=headers, verify=False) # 获取网页内容 div_bf = BeautifulSoup(get_re.text, ‘html.parser‘) # 获取小说章节 div = div_bf.find_all(‘dl‘, class_ = ‘chapterlist‘) print(div) # 使用正则匹配章节 cc = re.compile(r‘--使用正则匹配a标签中的链接--‘) for i in div_bf.find_all(‘a‘): # 获取a字段href属性,并遍历 j = cc.match(i[‘href‘]) if j: # 获取章节的分组信息 z = j.group() # 定义请求IP url = ‘--网址--‘+ z +‘‘ # 定义请求参数 headers = {‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36‘} # 执行请求 re = requests.get(url, headers, verify=False) # 获取网页内容 div_bf = BeautifulSoup(re.text,‘html.parser‘) # 提取小说章节名称 h1 = re.text.split(‘<h1>‘)[1].split(‘</h1>‘)[0] # 提取id为BookText的div中的数据 stp_div = re.text.split(‘<div id="BookText">‘)[1].split(‘</div>‘)[0] # 数据清洗 stp_div_001 = stp_div.replace(‘<br/>‘, ‘\n‘).replace(‘/n‘, ‘‘).replace(‘/t‘, ‘‘).replace(‘ ‘, ‘‘).replace(‘ ‘, ‘ ‘) # 打印章节名称及章节内容 log.info(h1) log.info(stp_div_001) time.sleep(1)
打印部分,使用了自己写的小代码,换成print即可
原文:https://www.cnblogs.com/linglongtouzianhongdou/p/13804868.html