crawlo 1.4.4__py3-none-any.whl → 1.4.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of crawlo might be problematic. Click here for more details.
- crawlo/__init__.py +11 -15
- crawlo/__version__.py +1 -1
- crawlo/commands/startproject.py +24 -0
- crawlo/core/engine.py +2 -2
- crawlo/core/scheduler.py +4 -4
- crawlo/crawler.py +8 -7
- crawlo/downloader/__init__.py +5 -2
- crawlo/downloader/cffi_downloader.py +3 -1
- crawlo/extension/__init__.py +2 -2
- crawlo/filters/aioredis_filter.py +8 -1
- crawlo/filters/memory_filter.py +8 -1
- crawlo/initialization/built_in.py +13 -4
- crawlo/initialization/core.py +5 -4
- crawlo/interfaces.py +24 -0
- crawlo/middleware/__init__.py +7 -4
- crawlo/middleware/middleware_manager.py +15 -8
- crawlo/middleware/proxy.py +171 -348
- crawlo/mode_manager.py +45 -11
- crawlo/network/response.py +374 -69
- crawlo/pipelines/mysql_pipeline.py +340 -189
- crawlo/pipelines/pipeline_manager.py +2 -2
- crawlo/project.py +2 -4
- crawlo/settings/default_settings.py +42 -30
- crawlo/stats_collector.py +10 -1
- crawlo/task_manager.py +2 -2
- crawlo/templates/project/items.py.tmpl +2 -2
- crawlo/templates/project/middlewares.py.tmpl +9 -89
- crawlo/templates/project/pipelines.py.tmpl +8 -68
- crawlo/templates/project/settings.py.tmpl +10 -55
- crawlo/templates/project/settings_distributed.py.tmpl +20 -22
- crawlo/templates/project/settings_gentle.py.tmpl +5 -0
- crawlo/templates/project/settings_high_performance.py.tmpl +5 -0
- crawlo/templates/project/settings_minimal.py.tmpl +25 -1
- crawlo/templates/project/settings_simple.py.tmpl +5 -0
- crawlo/templates/run.py.tmpl +1 -8
- crawlo/templates/spider/spider.py.tmpl +5 -108
- crawlo/tools/__init__.py +0 -11
- crawlo/utils/__init__.py +17 -1
- crawlo/utils/db_helper.py +226 -319
- crawlo/utils/error_handler.py +313 -67
- crawlo/utils/fingerprint.py +3 -4
- crawlo/utils/misc.py +82 -0
- crawlo/utils/request.py +55 -66
- crawlo/utils/selector_helper.py +138 -0
- crawlo/utils/spider_loader.py +185 -45
- crawlo/utils/text_helper.py +95 -0
- crawlo-1.4.6.dist-info/METADATA +329 -0
- {crawlo-1.4.4.dist-info → crawlo-1.4.6.dist-info}/RECORD +110 -69
- tests/authenticated_proxy_example.py +10 -6
- tests/bug_check_test.py +251 -0
- tests/direct_selector_helper_test.py +97 -0
- tests/explain_mysql_update_behavior.py +77 -0
- tests/ofweek_scrapy/ofweek_scrapy/items.py +12 -0
- tests/ofweek_scrapy/ofweek_scrapy/middlewares.py +100 -0
- tests/ofweek_scrapy/ofweek_scrapy/pipelines.py +13 -0
- tests/ofweek_scrapy/ofweek_scrapy/settings.py +85 -0
- tests/ofweek_scrapy/ofweek_scrapy/spiders/__init__.py +4 -0
- tests/ofweek_scrapy/ofweek_scrapy/spiders/ofweek_spider.py +162 -0
- tests/ofweek_scrapy/scrapy.cfg +11 -0
- tests/performance_comparison.py +4 -5
- tests/simple_crawlo_test.py +1 -2
- tests/simple_follow_test.py +39 -0
- tests/simple_response_selector_test.py +95 -0
- tests/simple_selector_helper_test.py +155 -0
- tests/simple_selector_test.py +208 -0
- tests/simple_url_test.py +74 -0
- tests/simulate_mysql_update_test.py +140 -0
- tests/test_asyncmy_usage.py +57 -0
- tests/test_crawler_process_import.py +39 -0
- tests/test_crawler_process_spider_modules.py +48 -0
- tests/test_crawlo_proxy_integration.py +8 -2
- tests/test_downloader_proxy_compatibility.py +24 -20
- tests/test_edge_cases.py +7 -5
- tests/test_encoding_core.py +57 -0
- tests/test_encoding_detection.py +127 -0
- tests/test_factory_compatibility.py +197 -0
- tests/test_mysql_pipeline_config.py +165 -0
- tests/test_mysql_pipeline_error.py +99 -0
- tests/test_mysql_pipeline_init_log.py +83 -0
- tests/test_mysql_pipeline_integration.py +133 -0
- tests/test_mysql_pipeline_refactor.py +144 -0
- tests/test_mysql_pipeline_refactor_simple.py +86 -0
- tests/test_mysql_pipeline_robustness.py +196 -0
- tests/test_mysql_pipeline_types.py +89 -0
- tests/test_mysql_update_columns.py +94 -0
- tests/test_optimized_selector_naming.py +101 -0
- tests/test_priority_behavior.py +18 -18
- tests/test_proxy_middleware.py +104 -8
- tests/test_proxy_middleware_enhanced.py +1 -5
- tests/test_proxy_middleware_integration.py +7 -2
- tests/test_proxy_middleware_refactored.py +25 -2
- tests/test_proxy_only.py +84 -0
- tests/test_proxy_with_downloader.py +153 -0
- tests/test_real_scenario_proxy.py +17 -17
- tests/test_response_follow.py +105 -0
- tests/test_response_selector_methods.py +93 -0
- tests/test_response_url_methods.py +71 -0
- tests/test_response_urljoin.py +87 -0
- tests/test_scrapy_style_encoding.py +113 -0
- tests/test_selector_helper.py +101 -0
- tests/test_selector_optimizations.py +147 -0
- tests/test_spider_loader.py +50 -0
- tests/test_spider_loader_comprehensive.py +70 -0
- tests/test_spiders/__init__.py +1 -0
- tests/test_spiders/test_spider.py +10 -0
- tests/verify_mysql_warnings.py +110 -0
- crawlo/middleware/simple_proxy.py +0 -65
- crawlo/tools/anti_crawler.py +0 -269
- crawlo/utils/class_loader.py +0 -26
- crawlo/utils/enhanced_error_handler.py +0 -357
- crawlo-1.4.4.dist-info/METADATA +0 -190
- tests/simple_log_test.py +0 -58
- tests/simple_test.py +0 -48
- tests/test_framework_logger.py +0 -67
- tests/test_framework_startup.py +0 -65
- tests/test_mode_change.py +0 -73
- {crawlo-1.4.4.dist-info → crawlo-1.4.6.dist-info}/WHEEL +0 -0
- {crawlo-1.4.4.dist-info → crawlo-1.4.6.dist-info}/entry_points.txt +0 -0
- {crawlo-1.4.4.dist-info → crawlo-1.4.6.dist-info}/top_level.txt +0 -0
- /tests/{final_command_test_report.md → ofweek_scrapy/ofweek_scrapy/__init__.py} +0 -0
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import scrapy
|
|
2
|
+
from urllib.parse import urljoin
|
|
3
|
+
|
|
4
|
+
class OfweekSpider(scrapy.Spider):
|
|
5
|
+
name = 'ofweek'
|
|
6
|
+
allowed_domains = ['ee.ofweek.com']
|
|
7
|
+
|
|
8
|
+
def start_requests(self):
|
|
9
|
+
"""生成初始请求"""
|
|
10
|
+
headers = {
|
|
11
|
+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
|
|
12
|
+
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
|
13
|
+
"Cache-Control": "no-cache",
|
|
14
|
+
"Connection": "keep-alive",
|
|
15
|
+
"Pragma": "no-cache",
|
|
16
|
+
"Referer": "https://ee.ofweek.com/CATList-2800-8100-ee-2.html",
|
|
17
|
+
"Sec-Fetch-Dest": "document",
|
|
18
|
+
"Sec-Fetch-Mode": "navigate",
|
|
19
|
+
"Sec-Fetch-Site": "same-origin",
|
|
20
|
+
"Sec-Fetch-User": "?1",
|
|
21
|
+
"Upgrade-Insecure-Requests": "1",
|
|
22
|
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
|
|
23
|
+
}
|
|
24
|
+
cookies = {
|
|
25
|
+
"__utmz": "57425525.1730117117.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)",
|
|
26
|
+
"Hm_lvt_abe9900db162c6d089cdbfd107db0f03": "1739244841",
|
|
27
|
+
"Hm_lvt_af50e2fc51af73da7720fb324b88a975": "1740100727",
|
|
28
|
+
"JSESSIONID": "FEA96D3B5FC31350B2285E711BF2A541",
|
|
29
|
+
"Hm_lvt_28a416fcfc17063eb9c4f9bb1a1f5cda": "1757477622",
|
|
30
|
+
"HMACCOUNT": "08DF0D235A291EAA",
|
|
31
|
+
"__utma": "57425525.2080994505.1730117117.1747970718.1757477622.50",
|
|
32
|
+
"__utmc": "57425525",
|
|
33
|
+
"__utmt": "1",
|
|
34
|
+
"__utmb": "57425525.2.10.1757477622",
|
|
35
|
+
"Hm_lpvt_28a416fcfc17063eb9c4f9bb1a1f5cda": "1757477628",
|
|
36
|
+
"index_burying_point": "c64d6c31e69d560efe319cc9f8be279f"
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
# 使用与Crawlo相同的页数进行公平测试
|
|
40
|
+
max_page = 50 # 原来是1851,现在改为50页进行测试
|
|
41
|
+
start_urls = []
|
|
42
|
+
for page in range(1, max_page + 1):
|
|
43
|
+
url = f'https://ee.ofweek.com/CATList-2800-8100-ee-{page}.html'
|
|
44
|
+
start_urls.append(url)
|
|
45
|
+
|
|
46
|
+
self.logger.info(f"生成了 {len(start_urls)} 个起始URL")
|
|
47
|
+
|
|
48
|
+
# 生成请求
|
|
49
|
+
for url in start_urls:
|
|
50
|
+
self.logger.info(f"添加起始URL: {url}")
|
|
51
|
+
try:
|
|
52
|
+
yield scrapy.Request(
|
|
53
|
+
url=url,
|
|
54
|
+
callback=self.parse,
|
|
55
|
+
headers=headers,
|
|
56
|
+
cookies=cookies,
|
|
57
|
+
dont_filter=True
|
|
58
|
+
)
|
|
59
|
+
except Exception as e:
|
|
60
|
+
self.logger.error(f"创建请求失败: {url}, 错误: {e}")
|
|
61
|
+
|
|
62
|
+
self.logger.info("start_requests方法执行完成")
|
|
63
|
+
|
|
64
|
+
def parse(self, response):
|
|
65
|
+
"""解析列表页"""
|
|
66
|
+
self.logger.info(f'正在解析页面: {response.url}')
|
|
67
|
+
|
|
68
|
+
# 检查响应状态
|
|
69
|
+
if response.status != 200:
|
|
70
|
+
self.logger.warning(f"页面返回非200状态码: {response.status}, URL: {response.url}")
|
|
71
|
+
return
|
|
72
|
+
|
|
73
|
+
# ================== 数据提取 ==================
|
|
74
|
+
try:
|
|
75
|
+
rows = response.xpath('//div[@class="main_left"]/div[@class="list_model"]/div[@class="model_right model_right2"]')
|
|
76
|
+
self.logger.info(f"在页面 {response.url} 中找到 {len(rows)} 个条目")
|
|
77
|
+
|
|
78
|
+
for row in rows:
|
|
79
|
+
try:
|
|
80
|
+
# 提取URL和标题
|
|
81
|
+
url = row.xpath('./h3/a/@href').extract_first()
|
|
82
|
+
title = row.xpath('./h3/a/text()').extract_first()
|
|
83
|
+
|
|
84
|
+
# 容错处理
|
|
85
|
+
if not url:
|
|
86
|
+
self.logger.warning(f"条目缺少URL,跳过")
|
|
87
|
+
continue
|
|
88
|
+
|
|
89
|
+
if not title:
|
|
90
|
+
self.logger.warning(f"条目缺少标题,跳过")
|
|
91
|
+
continue
|
|
92
|
+
|
|
93
|
+
# 确保 URL 是绝对路径
|
|
94
|
+
absolute_url = response.urljoin(url)
|
|
95
|
+
|
|
96
|
+
# 验证URL格式
|
|
97
|
+
if not absolute_url.startswith(('http://', 'https://')):
|
|
98
|
+
self.logger.warning(f"无效的URL格式,跳过: {absolute_url}")
|
|
99
|
+
continue
|
|
100
|
+
|
|
101
|
+
self.logger.info(f"提取到详情页链接: {absolute_url}, 标题: {title}")
|
|
102
|
+
yield scrapy.Request(
|
|
103
|
+
url=absolute_url,
|
|
104
|
+
meta={
|
|
105
|
+
"title": title.strip() if title else '',
|
|
106
|
+
"parent_url": response.url
|
|
107
|
+
},
|
|
108
|
+
callback=self.parse_detail
|
|
109
|
+
)
|
|
110
|
+
except Exception as e:
|
|
111
|
+
self.logger.error(f"处理条目时出错: {e}")
|
|
112
|
+
continue
|
|
113
|
+
|
|
114
|
+
except Exception as e:
|
|
115
|
+
self.logger.error(f"解析页面 {response.url} 时出错: {e}")
|
|
116
|
+
|
|
117
|
+
def parse_detail(self, response):
|
|
118
|
+
"""解析详情页"""
|
|
119
|
+
self.logger.info(f'正在解析详情页: {response.url}')
|
|
120
|
+
|
|
121
|
+
# 检查响应状态
|
|
122
|
+
if response.status != 200:
|
|
123
|
+
self.logger.warning(f"详情页返回非200状态码: {response.status}, URL: {response.url}")
|
|
124
|
+
return
|
|
125
|
+
|
|
126
|
+
try:
|
|
127
|
+
title = response.meta.get('title', '')
|
|
128
|
+
|
|
129
|
+
# 提取内容,增加容错处理
|
|
130
|
+
content_elements = response.xpath('//div[@class="TRS_Editor"]|//*[@id="articleC"]')
|
|
131
|
+
if content_elements:
|
|
132
|
+
content = content_elements.xpath('.//text()').extract()
|
|
133
|
+
content = '\n'.join([text.strip() for text in content if text.strip()])
|
|
134
|
+
else:
|
|
135
|
+
content = ''
|
|
136
|
+
self.logger.warning(f"未找到内容区域: {response.url}")
|
|
137
|
+
|
|
138
|
+
# 提取发布时间
|
|
139
|
+
publish_time = response.xpath('//div[@class="time fl"]/text()').extract_first()
|
|
140
|
+
if publish_time:
|
|
141
|
+
publish_time = publish_time.strip()
|
|
142
|
+
|
|
143
|
+
source = response.xpath('//div[@class="source-name"]/text()').extract_first()
|
|
144
|
+
|
|
145
|
+
# 创建数据项
|
|
146
|
+
item = {
|
|
147
|
+
'title': title.strip() if title else '',
|
|
148
|
+
'publish_time': publish_time if publish_time else '',
|
|
149
|
+
'url': response.url,
|
|
150
|
+
'source': source if source else '',
|
|
151
|
+
'content': content
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
# 验证必要字段
|
|
155
|
+
if not item['title']:
|
|
156
|
+
self.logger.warning(f"详情页缺少标题: {response.url}")
|
|
157
|
+
|
|
158
|
+
self.logger.info(f"成功提取详情页数据: {item['title']}")
|
|
159
|
+
yield item
|
|
160
|
+
|
|
161
|
+
except Exception as e:
|
|
162
|
+
self.logger.error(f"解析详情页 {response.url} 时出错: {e}")
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Automatically created by: scrapy startproject
|
|
2
|
+
#
|
|
3
|
+
# For more information about the [deploy] section see:
|
|
4
|
+
# https://scrapyd.readthedocs.io/en/latest/deploy.html
|
|
5
|
+
|
|
6
|
+
[settings]
|
|
7
|
+
default = ofweek_scrapy.settings
|
|
8
|
+
|
|
9
|
+
[deploy]
|
|
10
|
+
#url = http://localhost:6800/
|
|
11
|
+
project = ofweek_scrapy
|
tests/performance_comparison.py
CHANGED
|
@@ -79,7 +79,6 @@ class OfweekPerformanceSpider(Spider):
|
|
|
79
79
|
yield Request(url=url, callback=self.parse, headers=headers, cookies=cookies)
|
|
80
80
|
|
|
81
81
|
def parse(self, response):
|
|
82
|
-
from urllib.parse import urljoin
|
|
83
82
|
rows = response.xpath("//div[@class=\"main_left\"]/div[@class=\"list_model\"]/div[@class=\"model_right model_right2\"]")
|
|
84
83
|
|
|
85
84
|
for row in rows:
|
|
@@ -90,7 +89,7 @@ class OfweekPerformanceSpider(Spider):
|
|
|
90
89
|
if not url or not title:
|
|
91
90
|
continue
|
|
92
91
|
|
|
93
|
-
absolute_url = urljoin(
|
|
92
|
+
absolute_url = response.urljoin(url)
|
|
94
93
|
if not absolute_url.startswith(("http://", "https://")):
|
|
95
94
|
continue
|
|
96
95
|
|
|
@@ -171,11 +170,11 @@ def run_scrapy_test():
|
|
|
171
170
|
# 运行Scrapy测试
|
|
172
171
|
result = subprocess.run([
|
|
173
172
|
'scrapy', 'runspider',
|
|
174
|
-
'/
|
|
173
|
+
'D:/dowell/projects/Crawlo/tests/scrapy_comparison/ofweek_scrapy.py',
|
|
175
174
|
'-s', 'CONCURRENT_REQUESTS=8',
|
|
176
175
|
'-s', 'DOWNLOAD_DELAY=0.1',
|
|
177
176
|
'-s', 'LOG_LEVEL=ERROR'
|
|
178
|
-
], capture_output=True, text=True, timeout=300, cwd='
|
|
177
|
+
], capture_output=True, text=True, timeout=300, cwd='D:\dowell\projects\Crawlo')
|
|
179
178
|
|
|
180
179
|
end_time = time.time()
|
|
181
180
|
execution_time = end_time - start_time
|
|
@@ -205,7 +204,7 @@ def main():
|
|
|
205
204
|
print("=== Crawlo vs Scrapy 性能对比测试 ===")
|
|
206
205
|
|
|
207
206
|
# 创建测试目录
|
|
208
|
-
os.makedirs('
|
|
207
|
+
os.makedirs(os.path.join('D:\dowell\projects\Crawlo', 'tests', 'scrapy_comparison'), exist_ok=True)
|
|
209
208
|
|
|
210
209
|
# 运行测试
|
|
211
210
|
crawlo_time, crawlo_pages = run_crawlo_test()
|
tests/simple_crawlo_test.py
CHANGED
|
@@ -62,7 +62,6 @@ class OfweekSimpleSpider(Spider):
|
|
|
62
62
|
yield Request(url=url, callback=self.parse, headers=headers, cookies=cookies)
|
|
63
63
|
|
|
64
64
|
def parse(self, response):
|
|
65
|
-
from urllib.parse import urljoin
|
|
66
65
|
rows = response.xpath("//div[@class=\"main_left\"]/div[@class=\"list_model\"]/div[@class=\"model_right model_right2\"]")
|
|
67
66
|
|
|
68
67
|
for row in rows:
|
|
@@ -73,7 +72,7 @@ class OfweekSimpleSpider(Spider):
|
|
|
73
72
|
if not url or not title:
|
|
74
73
|
continue
|
|
75
74
|
|
|
76
|
-
absolute_url = urljoin(
|
|
75
|
+
absolute_url = response.urljoin(url)
|
|
77
76
|
if not absolute_url.startswith(("http://", "https://")):
|
|
78
77
|
continue
|
|
79
78
|
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
Response.follow 方法简单测试
|
|
5
|
+
"""
|
|
6
|
+
import sys
|
|
7
|
+
import os
|
|
8
|
+
|
|
9
|
+
# 添加项目根目录到Python路径
|
|
10
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
|
11
|
+
|
|
12
|
+
# 直接测试 urljoin 方法
|
|
13
|
+
from urllib.parse import urljoin
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_urljoin():
|
|
17
|
+
"""测试 urljoin 方法"""
|
|
18
|
+
base_url = "https://example.com/test"
|
|
19
|
+
|
|
20
|
+
# 测试绝对URL
|
|
21
|
+
absolute_url = urljoin(base_url, "https://other.com/page")
|
|
22
|
+
print(f"绝对URL: {absolute_url}")
|
|
23
|
+
assert absolute_url == "https://other.com/page"
|
|
24
|
+
|
|
25
|
+
# 测试相对URL
|
|
26
|
+
relative_url = urljoin(base_url, "/relative/path")
|
|
27
|
+
print(f"相对URL: {relative_url}")
|
|
28
|
+
assert relative_url == "https://example.com/relative/path"
|
|
29
|
+
|
|
30
|
+
# 测试复杂相对URL
|
|
31
|
+
complex_url = urljoin(base_url, "../other/path")
|
|
32
|
+
print(f"复杂相对URL: {complex_url}")
|
|
33
|
+
assert complex_url == "https://example.com/other/path"
|
|
34
|
+
|
|
35
|
+
print("所有测试通过!")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
if __name__ == '__main__':
|
|
39
|
+
test_urljoin()
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
简化测试Response类中的选择器方法
|
|
5
|
+
"""
|
|
6
|
+
import sys
|
|
7
|
+
import os
|
|
8
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
|
9
|
+
|
|
10
|
+
# 直接导入Response类
|
|
11
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'crawlo', 'network'))
|
|
12
|
+
from response import Response
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_response_selector_methods():
|
|
16
|
+
"""测试Response类中的选择器方法"""
|
|
17
|
+
print("测试Response类中的选择器方法...")
|
|
18
|
+
print("=" * 50)
|
|
19
|
+
|
|
20
|
+
# 创建测试HTML响应
|
|
21
|
+
html_content = """
|
|
22
|
+
<html>
|
|
23
|
+
<head>
|
|
24
|
+
<title>测试页面</title>
|
|
25
|
+
</head>
|
|
26
|
+
<body>
|
|
27
|
+
<div class="content">
|
|
28
|
+
<h1>主标题</h1>
|
|
29
|
+
<p class="intro">介绍段落</p>
|
|
30
|
+
<ul class="list">
|
|
31
|
+
<li>项目1</li>
|
|
32
|
+
<li>项目2</li>
|
|
33
|
+
<li>项目3</li>
|
|
34
|
+
</ul>
|
|
35
|
+
<a href="https://example.com" class="link">链接文本</a>
|
|
36
|
+
<img src="image.jpg" alt="图片描述" class="image">
|
|
37
|
+
</div>
|
|
38
|
+
</body>
|
|
39
|
+
</html>
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
# 创建Response对象
|
|
43
|
+
response = Response(
|
|
44
|
+
url="https://example.com/test",
|
|
45
|
+
body=html_content.encode('utf-8'),
|
|
46
|
+
headers={"content-type": "text/html; charset=utf-8"}
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
# 测试 extract_text (CSS选择器)
|
|
50
|
+
print("1. 测试 extract_text (CSS选择器):")
|
|
51
|
+
title_text = response.extract_text('title')
|
|
52
|
+
print(f" 标题文本: {title_text}")
|
|
53
|
+
|
|
54
|
+
h1_text = response.extract_text('.content h1')
|
|
55
|
+
print(f" H1文本: {h1_text}")
|
|
56
|
+
print()
|
|
57
|
+
|
|
58
|
+
# 测试 extract_text (XPath选择器)
|
|
59
|
+
print("2. 测试 extract_text (XPath选择器):")
|
|
60
|
+
title_text_xpath = response.extract_text('//title')
|
|
61
|
+
print(f" 标题文本: {title_text_xpath}")
|
|
62
|
+
|
|
63
|
+
h1_text_xpath = response.extract_text('//div[@class="content"]/h1')
|
|
64
|
+
print(f" H1文本: {h1_text_xpath}")
|
|
65
|
+
print()
|
|
66
|
+
|
|
67
|
+
# 测试 extract_texts
|
|
68
|
+
print("3. 测试 extract_texts:")
|
|
69
|
+
li_texts = response.extract_texts('.list li')
|
|
70
|
+
print(f" 列表项文本: {li_texts}")
|
|
71
|
+
print()
|
|
72
|
+
|
|
73
|
+
# 测试 extract_attr
|
|
74
|
+
print("4. 测试 extract_attr:")
|
|
75
|
+
link_href = response.extract_attr('.link', 'href')
|
|
76
|
+
print(f" 链接href: {link_href}")
|
|
77
|
+
|
|
78
|
+
img_alt = response.extract_attr('.image', 'alt')
|
|
79
|
+
print(f" 图片alt: {img_alt}")
|
|
80
|
+
print()
|
|
81
|
+
|
|
82
|
+
# 测试 extract_attrs
|
|
83
|
+
print("5. 测试 extract_attrs:")
|
|
84
|
+
all_links = response.extract_attrs('a', 'href')
|
|
85
|
+
print(f" 所有链接href: {all_links}")
|
|
86
|
+
|
|
87
|
+
all_images = response.extract_attrs('img', 'src')
|
|
88
|
+
print(f" 所有图片src: {all_images}")
|
|
89
|
+
print()
|
|
90
|
+
|
|
91
|
+
print("所有测试完成!")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
if __name__ == '__main__':
|
|
95
|
+
test_response_selector_methods()
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
简化选择器辅助工具测试
|
|
5
|
+
"""
|
|
6
|
+
from parsel import Selector
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
# 直接复制工具函数用于测试
|
|
10
|
+
def extract_text(elements, join_str=" "):
|
|
11
|
+
"""
|
|
12
|
+
从元素列表中提取文本并拼接
|
|
13
|
+
"""
|
|
14
|
+
texts = []
|
|
15
|
+
for element in elements:
|
|
16
|
+
if hasattr(element, 'xpath'):
|
|
17
|
+
element_texts = element.xpath('.//text()').getall()
|
|
18
|
+
else:
|
|
19
|
+
element_texts = [str(element)]
|
|
20
|
+
for text in element_texts:
|
|
21
|
+
cleaned = text.strip()
|
|
22
|
+
if cleaned:
|
|
23
|
+
texts.append(cleaned)
|
|
24
|
+
return join_str.join(texts)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def extract_texts(elements, join_str=" "):
|
|
28
|
+
"""
|
|
29
|
+
从元素列表中提取多个文本列表
|
|
30
|
+
"""
|
|
31
|
+
result = []
|
|
32
|
+
for element in elements:
|
|
33
|
+
if hasattr(element, 'xpath'):
|
|
34
|
+
texts = element.xpath('.//text()').getall()
|
|
35
|
+
else:
|
|
36
|
+
texts = [str(element)]
|
|
37
|
+
clean_texts = [text.strip() for text in texts if text.strip()]
|
|
38
|
+
if clean_texts:
|
|
39
|
+
result.append(join_str.join(clean_texts))
|
|
40
|
+
return result
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def extract_attr(elements, attr_name, default=None):
|
|
44
|
+
"""
|
|
45
|
+
从元素列表中提取单个元素的属性值
|
|
46
|
+
"""
|
|
47
|
+
if hasattr(elements, 'attrib'):
|
|
48
|
+
return elements.attrib.get(attr_name, default)
|
|
49
|
+
elif len(elements) > 0 and hasattr(elements[0], 'attrib'):
|
|
50
|
+
return elements[0].attrib.get(attr_name, default)
|
|
51
|
+
return default
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def extract_attrs(elements, attr_name):
|
|
55
|
+
"""
|
|
56
|
+
从元素列表中提取多个元素的属性值列表
|
|
57
|
+
"""
|
|
58
|
+
result = []
|
|
59
|
+
for element in elements:
|
|
60
|
+
if hasattr(element, 'attrib'):
|
|
61
|
+
attr_value = element.attrib.get(attr_name)
|
|
62
|
+
if attr_value is not None:
|
|
63
|
+
result.append(attr_value)
|
|
64
|
+
return result
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def is_xpath(query):
|
|
68
|
+
"""
|
|
69
|
+
判断查询语句是否为XPath
|
|
70
|
+
"""
|
|
71
|
+
return query.startswith(('/', '//', './'))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_selector_helper():
|
|
75
|
+
"""测试选择器辅助工具"""
|
|
76
|
+
print("测试选择器辅助工具...")
|
|
77
|
+
print("=" * 50)
|
|
78
|
+
|
|
79
|
+
# 创建测试HTML
|
|
80
|
+
html_content = """
|
|
81
|
+
<html>
|
|
82
|
+
<head>
|
|
83
|
+
<title>测试页面</title>
|
|
84
|
+
</head>
|
|
85
|
+
<body>
|
|
86
|
+
<div class="content">
|
|
87
|
+
<h1>主标题</h1>
|
|
88
|
+
<p class="intro">介绍段落</p>
|
|
89
|
+
<ul class="list">
|
|
90
|
+
<li>项目1</li>
|
|
91
|
+
<li>项目2</li>
|
|
92
|
+
<li>项目3</li>
|
|
93
|
+
</ul>
|
|
94
|
+
<a href="https://example.com" class="link">链接文本</a>
|
|
95
|
+
<img src="image.jpg" alt="图片描述" class="image">
|
|
96
|
+
</div>
|
|
97
|
+
</body>
|
|
98
|
+
</html>
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
selector = Selector(text=html_content)
|
|
102
|
+
|
|
103
|
+
# 测试 is_xpath
|
|
104
|
+
print("1. 测试 is_xpath:")
|
|
105
|
+
print(f" '/' 开头: {is_xpath('/')}")
|
|
106
|
+
print(f" '//' 开头: {is_xpath('//title')}")
|
|
107
|
+
print(f" './' 开头: {is_xpath('./div')}")
|
|
108
|
+
print(f" 'title' 开头: {is_xpath('title')}")
|
|
109
|
+
print()
|
|
110
|
+
|
|
111
|
+
# 测试 extract_text
|
|
112
|
+
print("2. 测试 extract_text:")
|
|
113
|
+
title_elements = selector.css('title')
|
|
114
|
+
title_text = extract_text(title_elements)
|
|
115
|
+
print(f" 标题文本: {title_text}")
|
|
116
|
+
|
|
117
|
+
h1_elements = selector.css('.content h1')
|
|
118
|
+
h1_text = extract_text(h1_elements)
|
|
119
|
+
print(f" H1文本: {h1_text}")
|
|
120
|
+
print()
|
|
121
|
+
|
|
122
|
+
# 测试 extract_texts
|
|
123
|
+
print("3. 测试 extract_texts:")
|
|
124
|
+
li_elements = selector.css('.list li')
|
|
125
|
+
li_texts = extract_texts(li_elements)
|
|
126
|
+
print(f" 列表项文本: {li_texts}")
|
|
127
|
+
print()
|
|
128
|
+
|
|
129
|
+
# 测试 extract_attr
|
|
130
|
+
print("4. 测试 extract_attr:")
|
|
131
|
+
link_elements = selector.css('.link')
|
|
132
|
+
link_href = extract_attr(link_elements, 'href')
|
|
133
|
+
print(f" 链接href: {link_href}")
|
|
134
|
+
|
|
135
|
+
img_elements = selector.css('.image')
|
|
136
|
+
img_alt = extract_attr(img_elements, 'alt')
|
|
137
|
+
print(f" 图片alt: {img_alt}")
|
|
138
|
+
print()
|
|
139
|
+
|
|
140
|
+
# 测试 extract_attrs
|
|
141
|
+
print("5. 测试 extract_attrs:")
|
|
142
|
+
all_links = selector.css('a')
|
|
143
|
+
all_hrefs = extract_attrs(all_links, 'href')
|
|
144
|
+
print(f" 所有链接href: {all_hrefs}")
|
|
145
|
+
|
|
146
|
+
all_images = selector.css('img')
|
|
147
|
+
all_srcs = extract_attrs(all_images, 'src')
|
|
148
|
+
print(f" 所有图片src: {all_srcs}")
|
|
149
|
+
print()
|
|
150
|
+
|
|
151
|
+
print("所有测试完成!")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
if __name__ == '__main__':
|
|
155
|
+
test_selector_helper()
|