Python爬虫之前期准备

本文详细介绍了Python爬虫开发中从环境配置到库安装的步骤,包括Selenium自动化测试、webdriver选择、requests和aiohttp请求库、lxml和BeautifulSoup解析、数据库如MySQL和MongoDB安装,以及Web框架Flask和Scrapy的使用。重点讲解了如何解决pip安装问题和选择合适的无头浏览器驱动。

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

0.以下流程参考工具书:《Python3网络爬虫开发实战》

作者的个人网站:《Python3网络爬虫开发实战》

收集各库的.whl的网站:https://www.lfd.uci.edu/~gohlke/pythonlibs

1.Python的安装和配置
1.1前期略
1.2pycharm
1.2.1导包问题
1.2.1.1alt+enter
1.2.1.2导包换源
Pycharm中导包失败的,解决方案:更换国内pip镜像源
2.selenium–>pip下载(下略)
2.1自动化测试工具

from selenium import webdriver
brower=webdriver.Chrome\Firefox\PhantomJS\Edge()

2.2selenium现在不支持phantomjs,3.4.3支持
2.3

pip uninstall selenium
pip install selenium==3.4.3

3.driver–>浏览器
3.1chromedriver–>chrome
3.1.1chrome无头模式代码
3.1.1.1
参考自:python 常见跳坑之selenium框架不支持phantomjs

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
#上面三行代码就是为了将Chrome不弹出界面,实现无界面爬取
browser = webdriver.Chrome(chrome_options=chrome_options)

3.2geckodriver–>firefox
3.3phantonjs
3.3.1无界面可脚本编程的webkit浏览器引擎
3.4edgedriver–>edge
3.4.1下载地址
https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
4.请求库
4.1request–>pip
4.2aiohttp–>pip

5.解析库的安装
5.1lxml–>pip
5.1.1支持HTML和XML的解析,XPath的解析方式
5.1.2pip安装失败
5.1.2.1Python–lxml库的简单介绍及基本使用
5.1.2.2
whl下载:https://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml

pip install lxml-4.6.3-cp310-cp310-win_amd64.whl

5.2beautiful soup–>pip
5.2.1pip install beautifulsoup4
5.3pyquery–>pip
5.4tesserocr–>浏览器安装tesseract,pip
5.4.1tesseract下载地址:https://digi.bib.uni-mannheim.de/tesseract/
5.4.2tesseract 安装及使用
windows 10环境下安装Tesseract-OCR与python集成
tesserocr 的安装
5.4.3
基于Python的OCR实现
6.数据库的安装
6.1mysql
6.2MongoDB
6.3redis
最新版Redis安装配置教程(Windows+Linux)
7.储存库的安装
6.1pymysql–>pip
6.2pymongo–>pip
6.3redis-py–>pip install redis
6.4RedisDump
7.web库的安装
7.1flask–>pip
7.2tornado–>pip
8.app相关库
8.1

9.爬虫框架
9.1pyspider–>pip 高版本python不要用这个
9.1.1pycurl错误
python3.6安装pyspider出现的问题(pycurl安装失败)和解决方案

pip install pycurl-7.44.1-cp310-cp310-win_amd64.whlpys

9.2Scrapy
Scrapy安装(windows)
9.3scrapy-splash–>docker
9.4scrapy-redis–>pip
10.部署相关库
10.1docker
下载地址:https://docs.docker.com/desktop/windows/install/
10.2scrapyd–>pip
10.3scrapyd-client–>pip
10.4scrapy API–>pip

pip install python-scrapyd-api

10.5scrapyrt–>pip
10.6gerapy–>pip

目录

### 获取中国福彩双色球中奖记录的 Python 爬虫实现 为了通过 Python 实现对中国福利彩票官网上的双色球中奖数据进行爬取,可以采用 `requests` 和 `BeautifulSoup` 库来完成网页请求和解析的任务。以下是具体的解决方案: #### 1. 准备工作 在开始编写代码之前,需安装必要的库: - **Requests**: 处理 HTTP 请求。 - **BeautifulSoup (bs4)**: 解析 HTML 文档。 可以通过以下命令安装这些依赖项: ```bash pip install requests beautifulsoup4 ``` --- #### 2. 定位目标网站结构 假设目标是中国福利彩票官方网站的数据页面[^1],需要先分析其 URL 结构以及 HTML 的标签布局。通常情况下,该类站点会提供按日期查询的功能或者分页展示历史开奖信息。 例如,如果每期开奖结果都存储在一个固定的表格中,则可通过观察 `<table>` 或其他容器元素找到对应的字段名称及其 CSS 类名或 ID 属性。 > 注意事项:某些政府机构或官方平台可能设置反爬机制(如验证码验证),因此建议遵循 robots.txt 文件规定并适当降低访问频率以免触发封锁措施。 --- #### 3. 编写核心逻辑 下面是一个简单的脚本框架用于抓取最近六个月内的所有双色球开奖号码及相关详情: ```python import requests from bs4 import BeautifulSoup from datetime import datetime, timedelta def fetch_lottery_results(start_date=None, end_date=None): base_url = "https://www.example.com/ssq/" # 替换为目标实际网址 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' } results = [] current_date = start_date or (datetime.now() - timedelta(days=180)).strftime('%Y-%m-%d') while True: url = f"{base_url}?date={current_date}" response = requests.get(url, headers=headers) if not response.ok: break soup = BeautifulSoup(response.text, 'html.parser') table_rows = soup.select('tr') # 假设每一行代表一期结果 for row in table_rows: cells = row.find_all('td') issue_number = cells[0].text.strip() red_balls = [int(ball.text) for ball in cells[1].find_all('span', class_='red')] blue_ball = int(cells[2].find('span', class_='blue').text) draw_date = cells[-1].text.strip() result_entry = { 'issue': issue_number, 'draw_date': draw_date, 'red_balls': red_balls, 'blue_ball': blue_ball } results.append(result_entry) next_day = (datetime.strptime(current_date, '%Y-%m-%d') + timedelta(days=1)) current_date = next_day.strftime('%Y-%m-%d') if end_date and next_day >= datetime.strptime(end_date, '%Y-%m-%d'): break return results if __name__ == "__main__": data = fetch_lottery_results() for entry in data[:5]: # 打印前五条记录作为示例 print(entry) ``` 此函数接受两个参数——起始时间和结束时间,默认从当前日期向前推算半年的时间范围。它逐日遍历指定区间内的每一天,并尝试加载对应的结果列表;当遇到错误状态码时停止循环以防无限运行下去。 --- #### 4. 存储与处理数据 收集到原始 JSON 数据之后,可以根据需求进一步加工成更易读的形式或将它们出至 CSV 文件以便后续统计分析之用。 保存为 Excel 表格样式的例子如下所示: ```python import pandas as pd df = pd.DataFrame(data) output_path = './double_color_ball_results.csv' df.to_csv(output_path, index=False, encoding='utf_8_sig') print(f"Data has been saved to {output_path}") ``` --- ### 提醒与注意事项 由于网络环境变化莫测加上不同地区法律法规差异较大,在正式部署任何自动化工具前务必确认自己行为合法合规且尊重原作者版权条款。此外还应考虑到服务器负载能力合理安排调用量级以减少不必要的麻烦发生几率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值