Python爬虫Demo

Python爬虫Demo   

import json
import os

import pymysql
import requests
from lxml import etree
import time
import csv


# 定义函数抓取
def crow_first(a):
    # 构造每一页的url变化
    url = 'https://*******/portal_server/lawyer/query/'+str(a or '')
    r = requests.get(url)
    # 指定编码方式,不然会出现乱码
    r.encoding = 'utf-8'

    # 将 Python 字典类型转换为 JSON 对象
    json_str = json.dumps(r.json())

    # 将 JSON 对象类型转换为 Python 字典
    user_dic = json.loads(json_str)

    a=str(a or '')
    nameStr=str(user_dic['data']['name'] or '')
    licenseNumber=str(user_dic['data']['licenseNumber']or '')
    description=str(user_dic['data']['description']or '')
    phone=str(user_dic['data']['phone']or '')
    photo=str(user_dic['data']['photo']['name']or '')

    config = {
        'host': '127.0.0.1'
        , 'user': 'root'
        , 'password': 'root'
        , 'database': 'test'
        , 'charset': 'utf8'
        , 'port': 3306  # 注意端口为int 而不是str
    }

    db = pymysql.connect(**config)
    cursor = db.cursor()

    try:
        db.select_db("test")
        sql = "INSERT INTO test.cdtf_data(id,name,licenseNumber,description,phone,photo)VALUES(%s,%s,%s,%s,%s,%s)"
        cursor.execute(sql, (a, nameStr, licenseNumber, description,phone,photo))
        db.commit()
        print('插入数据成功')
    except Exception as e:
        db.rollback()
        print("插入数据失败")
        print('Failed:', e)

    cursor.close()
    db.close()
    time.sleep(3)
#图片保存
    url = "https://cld.cdtf.gov.cn/attachment_server/"+photo
    root = "d://pics//";
    path = root + url.split('/')[-1]
    try:
        if not os.path.exists(root):
            os.mkdir(root)
        if not os.path.exists(path):
            r = requests.get(url)
            with open(path, 'wb') as f:
                f.write(r.content)
                f.close()
                print("图片保存cg")
        else:
            print("保存失败")
    except:
        print('爬取失败')

# 定义函数抓取
def crow_list(a):
    # 分页查询
    url = 'https://******/portal_server/lawyer/query/page?pageNum='+str(a or '')
    r = requests.get(url)
    # 指定编码方式,不然会出现乱码
    r.encoding = 'utf-8'

    # 将 Python 字典类型转换为 JSON 对象
    json_str = json.dumps(r.json())

    # 将 JSON 对象类型转换为 Python 字典
    user_dic = json.loads(json_str)

    print("------当前页数为" + str(a));
    list=user_dic['data']['records']
    for user in list:
        print('当前律师ID:'+user['id'])
        crow_first(user['id'])

if __name__ == '__main__':
    for i in range(150, 2399):#2399为每页十条的总页数。
        crow_list(i)

<think>嗯,用户想找Python爬虫的示例代码或者教程。首先,我需要根据用户提供的引用内容来整理相关信息。引用1提到了三个使用urllib2库的爬虫项目实例,不过urllib2现在在Python3中已经被urllib.request取代了,可能需要提醒用户注意版本问题。引用2推荐了10个入门实例,并提到了Python在不同领域的应用,这里可能需要强调基础学习的重要性。引用3则介绍了常用的库,比如requests、BeautifulSoup和Scrapy,这些都是现在比较流行的工具。 用户可能需要从简单到复杂的例子,所以应该先介绍基本的库,再给一些具体的代码示例。比如用requests获取网页内容,再用BeautifulSoup解析。另外,考虑到用户可能对爬虫框架感兴趣,可以提到Scrapy的简单例子,但可能不需要太深入,毕竟用户可能刚入门。 需要注意用户可能遇到的常见问题,比如反爬虫机制,或者如何处理动态加载的内容。这时候可能需要建议使用Selenium或者Scrapy-Splash这样的工具,但引用中没有提到这些,所以或许应该保持在引用提到的内容范围内,或者适当补充常识性的建议。 另外,引用1和2都提到了学习资料,可以推荐用户参考这些资料,并指出引用来源。同时,用户可能需要教程链接,但根据引用内容,可能无法提供外部链接,所以需要引导用户根据提到的资料名称去查找。 最后,生成相关问题的时候,要围绕爬虫的基础知识、库的使用、反爬策略、数据处理和应用场景等方面提问,帮助用户深入理解。</think>### Python爬虫示例代码及教程推荐 #### 一、基础爬虫示例(静态网页) **使用requests + BeautifulSoup** 1. 安装依赖库: ```bash pip install requests beautifulsoup4 ``` 2. 代码示例(取豆瓣电影TOP250标题): ```python import requests from bs4 import BeautifulSoup url = "https://movie.douban.com/top250" headers = {"User-Agent": "Mozilla/5.0"} response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, "html.parser") for item in soup.find_all("div", class_="hd"): title = item.a.span.text print(title) ``` **说明**:通过解析HTML结构提取电影标题[^3]。 #### 二、进阶爬虫框架(Scrapy) **Scrapy框架使用步骤** 1. 安装Scrapy: ```bash pip install scrapy ``` 2. 创建Scrapy项目: ```bash scrapy startproject movie_crawler ``` 3. 编写爬虫核心代码(示例): ```python import scrapy class DoubanSpider(scrapy.Spider): name = "douban" start_urls = ["https://movie.douban.com/top250"] def parse(self, response): for movie in response.css("div.hd"): yield {"title": movie.css("a span::text").get()} ``` **特点**:Scrapy提供自动化的请求调度和数据处理管道。 #### 三、教程推荐 1. **《Python爬虫项目实例》** - 包含urllib2/requests库的基础用法(需注意Python2/3差异)[^1] 2. **《10个Python爬虫入门实例》** - 覆盖简单图片取、数据存储等场景[^2] 3. **官方文档** - BeautifulSoup文档:https://www.crummy.com/software/BeautifulSoup/ - Scrapy中文文档:https://scrapy-chs.readthedocs.io #### 四、注意事项 1. 遵守目标网站的`robots.txt`协议 2. 添加延时防止被封IP(如`time.sleep(2)`) 3. 动态网页建议配合Selenium使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值