爬取知乎发现首页 requests+pyquery

博主分享了初次尝试爬虫的经历,利用requests和pyquery库抓取了知乎首页的内容,并将结果保存到TXT文件。文中提及,如要导出到CSV文件,需要注意newline=''参数的设置以避免自动换行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本人的第一次爬虫,爬取后的文章保存在txt文件里。

参考:python3 网络爬虫开发实战

import requests
from requests import RequestException
from pyquery import PyQuery as pq

url = 'https://www.zhihu.com/explore'
headers = {
    'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit'
        '/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
}

def get_one_page(url):
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return None


def write_result(content):
    doc = pq(content)
    items  = doc('.explore-tab .feed-item').items()
    with open('explore.txt','a',encoding='utf-8') as file:
        for item in items:
            question = item.find('h2').text()
     
Python爬取乎并可视化通常涉及几个步骤,包括使用网络请求库如requests获取网页内容,解析HTML或JSON数据使用BeautifulSoup或PyQuery等库,然后存储数据,最后使用数据可视化工具如matplotlib、seaborn或Plotly展示结果。以下是一个简化的示例,假设我们只关注爬取文章标题: ```python # 导入必要的库 import requests from bs4 import BeautifulSoup import matplotlib.pyplot as plt # 模拟登录或使用公开API(如果可用) # 这部分取决于具体的API策略,这里暂不显示 url = 'https://www.zhihu.com/topic/xxxxx/top-answers' # 替换为你要抓取的主题URL response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 解析HTML找到文章标题 titles = [title.text for title in soup.find_all('h2', class_='QuestionItem-title')] # 数据存储,这里可以用list或DataFrame data = [{'title': title} for title in titles] # 对于可视化,我们可以统计标题数量分布 title_counts = {title: data.count(title) for title in set(titles)} # 绘制条形图 plt.figure(figsize=(10, 6)) plt.bar(title_counts.keys(), title_counts.values()) plt.xlabel('标题') plt.ylabel('次数') plt.title('乎主题热门文章标题统计') plt.show() ``` 注意这只是一个基本框架,实际操作可能需要处理反虫机制、分页加载、错误处理等问题。对于敏感信息或频繁访问,记得遵守乎的robots.txt规则以及使用合适的用户代理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值