首页 > 其他 > 详细

爬虫初次接触

时间:2020-10-12 23:46:02      阅读:35      评论:0      收藏:0      [点我收藏+]
下面以某小说网站为例:
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(&nbsp;,  )

        # 打印章节名称及章节内容
        log.info(h1)
        log.info(stp_div_001)
        time.sleep(1)

打印部分,使用了自己写的小代码,换成print即可

爬虫初次接触

原文:https://www.cnblogs.com/linglongtouzianhongdou/p/13804868.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!