python爬虫demo

# coding:utf-8
import requests
from bs4 import BeautifulSoup
import pandas

# 反扒使用 http://www.user-agent.cn/
ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0'
# 需要抓取的url
url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html'
r = requests.get(url, headers={'User-Agent': ua})
r.encoding = 'utf-8'
# 获取整个页面的内容
html = r.text
soup = BeautifulSoup(html, 'html.parser')
# 定义需要导出的列头,内容
# 列名
columms_str = []
# 排名
ranking_str = []
# 学校名称
school_str = []
# 省份
province_str = []
# 总分
totalscore_str = []
# 获取页面的table
table = soup.find("table", class_='table table-small-font table-bordered table-striped')
# print(table)
# 获取列头
columms = table.thead.tr.find_all("th")
# 取前4列既满足要求
for index in range(0, 4):
    # 列名
    columms_str.append(columms[index].string)
    # 打印列名
    print(columms[index].string)
# 获取表格主体中的所有行
trs = table.tbody.find_all("tr", class_='alt')
# print(trs)
for tr in trs:
    # 获取每行的所有列
    tds = tr.find_all("td")
    # 取前4列既满足要求
    for index in range(0, 4):
        # 存储列的内容
        td = ''
        if index == 1:
            # 获取单元格内容
            td = tds[index].div.string
            # 学校名称
            school_str.append(td)
        else:
            # 获取单元格内容
            td = tds[index].string
            if index == 0:
                # 排名
                ranking_str.append(td)
            if index == 2:
                # 省份
                province_str.append(td)
            if index == 3:
                # 总分
                totalscore_str.append(td)
        # 打印每个单元格的内容
        print(td)

# 输出到Excel中
# 数据
data = {columms_str[0]: ranking_str, columms_str[1]: school_str, columms_str[2]: province_str, columms_str[3]: totalscore_str}
# 存储路径(可固定路径:D:\\www\\result.xlsx)
filepath = 'result.xlsx'
df = pandas.DataFrame(data)
# 写入excel
df.to_excel(filepath, sheet_name='中国最好大学排名', encoding='utf-8', index=False, header=True)
print('Success')
 

<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、付费专栏及课程。

余额充值