python 爬取 csdn 网站信息

本文介绍了一个使用Python进行优快云网站信息爬取的例子。通过requests和BeautifulSoup库来抓取网页内容,并利用多进程提高爬取效率。文章详细展示了如何从代理IP网站获取IP并验证其有效性。

python 爬取 csdn 网站信息

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests
from bs4 import BeautifulSoup
import multiprocessing
import time

success_num = 0

CONSTANT = 0


def getProxyIp():
    global CONSTANT
    proxy = []
    for i in range(1, 80):
        print(i)
        header = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36'}
        r = requests.get('http://www.xicidaili.com/nt/{0}'.format(str(i)), headers=header)
        html = r.text
        soup = BeautifulSoup(html, 'lxml')
        table = soup.find('table', attrs={'id': 'ip_list'})
        tr = table.find_all('tr')[1:]

        # 解析得到代理ip的地址,端口,和类型
        for item in tr:
            tds = item.find_all('td')
            print(tds[1].get_text())
            temp_dict = {}
            kind = tds[5].get_text().lower()
            # exit()
            if 'http' in kind:
                temp_dict['http'] = "http://{0}:{1}".format(tds[1].get_text(), tds[2].get_text())
            if 'https' in kind:
                temp_dict['https'] = "https://{0}:{1}".format(tds[1].get_text(), tds[2].get_text())

            proxy.append(temp_dict)
    return proxy


def brash(proxy_dict):
    header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '
                            'AppleWebKit/537.36 (KHTML, like Gecko) '
                            'Ubuntu Chromium/44.0.2403.89 '
                            'Chrome/44.0.2403.89 '
                            'Safari/537.36',
              'Referer': 'https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&tn=baidu&wd=csdn%20%E6%80%9D%E6%83%B3%E7%9A%84%E9%AB%98%E5%BA%A6%20csdnzouqi&oq=csdn%20%E6%80%9D%E6%83%B3%E7%9A%84%E9%AB%98%E5%BA%A6&rsv_pq=fe7241c2000121eb&rsv_t=0dfaTIzsy%2BB%2Bh4tkKd6GtRbwj3Cp5KVva8QYLdRbzIz1CCeC1tOLcNDWcO8&rqlang=cn&rsv_enter=1&rsv_sug3=11&rsv_sug2=0&inputT=3473&rsv_sug4=3753'

              }
    try:
        r = requests.get("xxxx", headers=header,
                         proxies=proxy_dict, timeout=10)
        print(r.status_code)
    except BaseException as e:
        print("failed", e)
    else:
        print("successful")
    time.sleep(0.5)
    return None


if __name__ == '__main__':
    i = 0
    t = 0
    final = 10  # 输入数字代表要获取多少次代理ip
    while t < final:
        t += 1
        proxies = getProxyIp()  # 获取代理ip网站上的前12页的ip
        # 为了爬取的代理ip不浪费循环5次使得第一次的不能访问的ip尽可能利用
        # print CONSTANT
        for i in range(5):
            i += 1
            # 多进程代码开了32个进程
            pool = multiprocessing.Pool(processes=32)
            results = []
            for i in range(len(proxies)):
                results.append(pool.apply_async(brash, (proxies[i],)))
            for i in range(len(proxies)):
                results[i].get()
            pool.close()
            pool.join()
        i = 0
        time.sleep(10)

 完整代码下载:https://github.com/tanjunchen/SpiderProject/tree/master/csdn

 

### 实现优快云网站信息爬取 为了实现对优快云网站信息爬取,可以利用`requests`库发送HTTP请求并获取页面内容,再借助`BeautifulSoup`解析HTML文档结构。对于更复杂的交互逻辑或动态加载的内容,则可能需要用到Selenium这样的工具模拟浏览器行为。 #### 准备工作 安装必要的Python库: ```bash pip install requests beautifulsoup4 pandas selenium openpyxl ``` #### 发送HTTP请求 构建一个简单的函数来发起GET请求,并处理可能出现的异常情况[^2]。 ```python import requests from bs4 import BeautifulSoup def fetch_page(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', } try: resp = requests.get(url, headers=headers) if resp.status_code == 200: return resp.text else: print(f"Failed to load page {url}, status code: {resp.status_code}") return None except Exception as e: print(f"Error occurred while fetching URL {url}: ", str(e)) return None ``` #### 解析网页内容 定义另一个辅助方法用于提取所需字段,比如文章标题、类别、创建时间和阅读量等信息[^1]。 ```python def parse_article_info(html_content): soup = BeautifulSoup(html_content, "html.parser") articles = [] article_elements = soup.select('.article-item-box') for element in article_elements: title = element.find('h4').get_text(strip=True) category = element.select_one('.category').get_text(strip=True) if element.select_one('.category') else '' created_at = element.select_one('.date').get_text(strip=True) read_count = int(element.select_one('.read-num').get_text().replace('阅读数:', '').strip()) articles.append({ 'title': title, 'type': category, 'created_time': created_at, 'reads': read_count }) return articles ``` #### 存储到Excel文件 最后一步是将收集到的数据导出成Excel表格格式以便后续查看和分析[^3]。 ```python import pandas as pd def save_to_excel(data_list, filename='output.xlsx'): df = pd.DataFrame(data_list) with pd.ExcelWriter(filename, engine='openpyxl', mode='w') as writer: df.to_excel(writer, index=False) if __name__ == '__main__': target_url = 'https://blog.csdn.net/some_user_id/article/list' html_data = fetch_page(target_url) if html_data is not None: parsed_articles = parse_article_info(html_data) save_to_excel(parsed_articles, './csdn_articles.xlsx') print("Data has been successfully saved.") ``` 此脚本会访问指定用户的个人主页链接(需替换为实际的目标URL),从中抽取公开发布的每篇文章的相关元数据,并最终把这些记录整理好存入本地磁盘上的Excel电子表单里。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

远方的飞猪

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

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

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

打赏作者

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

抵扣说明:

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

余额充值