项目代码:爬取糗事百科,并生成相应的csv文件

爬取糗事百科,并生成相应的csv文件

代码:

import csv
import requests
from lxml import etree

Headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36 Edg/89.0.774.48"
}
Base_url = "https://www.qiushibaike.com"

c = open("test.csv", "w",encoding='utf-8',newline='')
writer = csv.writer(c)
writer.writerow(['题目','段子内容'])

qiushis = []

def spider():
    url = "https://www.qiushibaike.com/text/page/{}/"
    # 循环列表页
    for x in range(1, 2):
        url = url.format(x)
        detail_urls = get_detail_urls(url)
        #  循环详情页的
        for detail_url in detail_urls:
            qiushi = parse_detail(detail_url)
            qiushis.append(qiushi)
            print(qiushi)

    c.close()

        # 解析详情页的内容
def parse_detail(url):
    qiushi = {}
    resp = requests.get(url, headers=Headers)
    text = resp.content.decode("utf-8")
    html = etree.HTML(text)
    DivE = html.xpath("//div[@class='col1 new-style-col1']")[0]
    title = DivE.xpath("//h1[@class='article-title']/text()")[0]
    qiushi["title"] = title.replace('\n\n', '')
    content = DivE.xpath("//div[@class='content']/text()")[0]
    qiushi["content"] = content
    templist = []
    templist.append(qiushi["title"])
    templist.append(qiushi["content"])
    writer.writerow(templist)
    return qiushi

# 拿到详情页的地址
def get_detail_urls(url):
    res = requests.get(url, headers=Headers)
    text = res.text

    html = etree.HTML(text)
    detail_urls = html.xpath("//div[@class='article block untagged mb15 typs_hot']/a[@class='contentHerf']/@href")
    detail_urls = map(lambda url: Base_url + url, detail_urls)
    return detail_urls

print(__name__)
if __name__ == '__main__':
    spider()

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

S1901

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值