欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python糗事百科爬虫

程序员文章站 2024-02-05 11:14:34
糗事百科爬虫-通过面向对象实现糗事百科页面爬取使用xpath解析页面import requestsfrom lxml import etree class Qiubai: def __init__(self): self.temp_url = "https://www.qiushibaike.com/hot/page/{}" self.headers = {"user-agent": "Mozilla/5.0 (Macintosh; Intel Ma...

糗事百科爬虫

-通过面向对象实现糗事百科页面爬取

  • 使用xpath解析页面

Python糗事百科爬虫

import requests
from lxml import etree 

class Qiubai:
    def __init__(self):
        self.temp_url = "https://www.qiushibaike.com/hot/page/{}"
        self.headers = {"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.68 Safari/537.36"}
    
    def get_url_list(self):
        return [self.temp_url.format(i) for i in range(1,14)]
    
    def parse_url(self,url):
        response = requests.get(url,headers=self.headers)
        return response.content.decode()
    def get_content_list(self,html_str):
        html = etree.HTML(html_str)
        div_list = html.xpath("//div[@class='col1 old-style-col1']/div")
        content_list = []
        for div in div_list:
            item = {}
            item['user_name'] = div.xpath(".//h2/text()")[0].strip()
            item['content'] = [i.strip() for i in div.xpath(".//div[@class='content']/span/text()")]
            content_list.append(item)
        return content_list
    def save_content_list(self,content_list):
        for content in content_list:
            print(content)


    def run(self):
        #1. 准备url列表
        url_list = self.get_url_list()
        #2. 遍历发送请求,获取响应
        for url in url_list:
            html_str = self.parse_url(url) 
            #3. 提取数据
            content_list = self.get_content_list(html_str)
            # 4.保存数据
            self.save_content_list(content_list)

if __name__ == "__main__":
    qiubai = Qiubai()
    qiubai.run()


本文地址:https://blog.csdn.net/qq_44224678/article/details/107154891