python - Scrapy:检查页面是否包含 HTML 表单元素
问题描述
我需要一个scrapy 脚本来探索整个网站,并且只保存其中包含form
HTML 标记的页面。
这是我目前无法正常工作的方法
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class MySpider(CrawlSpider):
name = 'mps'
allowed_domains = ['some.url.com']
start_urls = ['https://some.url.com/']
rules = (
Rule(LinkExtractor(), callback='parse_item', follow=True),
)
def parse_item(self, response):
hasForm = response.xpath("//form[@id = 'aspnetForm']/form").extract_first(default='not-found')
if hasForm == 'not-found':
pass
else:
filename = response.url.split("/")[-2] + '.html'
with open(filename, 'wb') as f:
f.write(response.body)
pass
更新:
我还需要用form
特定的 id排除
解决方案
例子
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class MySpider(CrawlSpider):
name = 'mps'
allowed_domains = ['some.url.com']
start_urls = ['https://some.url.com/']
rules = (
Rule(LinkExtractor(), callback='parse_item', follow=True),
)
def parse_item(self, response):
hasForm = response.xpath("//form").extract_first(default='not-found')
if hasForm != 'not-found':
page = response.url.split("/")[-2]
filename = 'test-%s.html' % page
with open(filename, 'wb') as f:
f.write(response.body)
推荐阅读
- javascript - 如何通过递归减少传播
- python - ImportError: 无法导入名称 _hierarchy 或 DLL 加载失败:%1 不是有效的 Win32 应用程序
- javascript - 对象,每个和 DOM 操作
- r - 如何从 R 中 RollCor 的输出中切片数组?
- android - 在android中自动在后台发送短信
- node.js - 我已经制作了正确的 Procfile,但在仪表板中没有看到工人测功机
- r - 将子文件夹中的excel文件合并到R中的一个数据框中
- flask - Flask 可选上传文件
- mod-security - ModSecurity规则中感叹号的含义
- selenium - Selenium 错误没有方法签名:org.openqa.selenium.chrome.ChromeDriver.find_element_by_class_name() 适用于参数