Python爬虫实例-获取页面内大量url里的数据
一、前言
本章以某政府公开招标中标网站为实例,进行某一个指定类别的中标数据挖掘,并将这些数据存储到excel表格中。
网站:http://jsggzy.jszwfw.gov.cn/jyxx/tradeInfonew.html
需要挖掘内容:近两三个月的交通工程的中标结果公告(里的详细内容)
在使用python爬虫过程中有以下几点要注意!!
(1)遵守网站的 robots.txt
大多数网站都会有一个 robots.txt 文件,指定爬虫允许访问的路径。确保爬虫遵守这些规则,以避免不必要的法律问题和道德冲突。
(2)控制请求频率
不要频繁地向服务器发送请求,以免给服务器带来过大的压力,导致 IP 被封禁。可以使用 time.sleep() 方法在请求之间添加延迟。
昨天我抓了一天,下午的时候请求中断了一次。过了一会再试就好了~
import time
time.sleep(1) # 休眠 1 秒
(3)处理异常
网络请求过程中可能会发生各种异常情况,如连接超时、目标网页不可访问等。确保代码有适当的异常处理机制。
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f'Error: {e}')
二、Python爬虫简介
Python 爬虫是一种用于自动化网页数据抓取的工具。使用 Python 进行网页爬虫的过程一般包括以下几个步骤:
(1)发送请求:向目标网页发送 HTTP 请求,并获取响应内容。
(2)解析内容:将获取到的网页内容进行解析,提取出需要的数据。
(3)保存数据:将提取到的数据进行存储,通常保存在文件、数据库等。
最常使用的库有 requests 和 BeautifulSoup 库,需要安装。可以使用以下命令进行安装:
pip install requests
pip install beautifulsoup4
对于更复杂的需求,可以考虑使用以下工具:
Scrapy:一个功能强大的爬虫框架,适用于大规模爬取。
Selenium:适用于需要处理动态内容或模拟用户操作的场景。
lxml:高性能的 HTML/XML 解析库。
三、代码解析
导入相应的库
import time
import requests
import pandas as pd
from datetime import datetime, timedelta
import threading
from bs4 import BeautifulSoup
import re
import json
from dateutil.relativedelta import relativedelta
点开页面,发现里面有大量的标题,每个中标公告标题都对应一个url。先获取页面里的所有url。
#提取页面里的URL地址
def get_content_list(start_page,url_list):
now = datetime.now()
end_of_day =now.replace(hour=23, minute=59, second=59, microsecond=0)
# Calculate the date three months ago
three_months_ago = now - relativedelta(months=3)
# Set the time to 00:00:00 for three months ago
start_of_date = three_months_ago.replace(hour=0, minute=0, second=0, microsecond=0)
# Convert datetime objects to strings
end_of_day_str = end_of_day.strftime("%Y-%m-%d %H:%M:%S")
start_of_date_str = start_of_date.strftime("%Y-%m-%d %H:%M:%S")
json_payload_template = '''{
"token": "",
"pn": %d,
"rn": 20,
"sdt": "",
"edt": "",
"wd": "",
"inc_wd": "",
"exc_wd": "",
"fields": "title",
"cnum": "001",
"sort": "{\\"infodatepx\\":\\"0\\"}",
"ssort": "title",
"cl": 200,
"terminal": "",
"condition": [
{
"fieldName": "categorynum",
"isLike": true,
"likeType": 2,
"equal": "003002"
}
],
"time": [
{
"fieldName": "infodatepx",
"startTime": "%s",
"endTime": "%s"
}
],
"highlights": "title",
"statistics": null,
"unionCondition": null,
"accuracy": "",
"noParticiple": "1"