シーンの説明
Python クローラーを使用する場合、多くの場合、クロールされたデータをクリーンアップして、不要なコンテンツを除外する必要があります。正規化 () は、クロール結果がテキストre.sub()
であるデータのデータ クリーニングによく使用されますが、クロール結果がHTMLであるデータの場合、データ クリーニングに正規化を引き続き使用すると、半分の労力で 2 倍の結果が得られることがよくあります。結果はHTM L のデータをクリーンアップするにはどうすればよいですか?
コード例
# -*- coding: utf-8 -*-
import scrapy
import htmlmin
from lxml import etree
from lxml import html
from html import unescape
class TestSpider(scrapy.Spider):
name = 'test'
allowed_domains = ['www.gongkaoleida.com']
start_urls = ['https://www.gongkaoleida.com/article/869186']
# start_urls = ['https://www.gongkaoleida.com/article/869244']
def parse(self, response):
content = response.xpath('//article[@class="detail-info"]').getall()[0].replace('\n', '').replace('\r', '')
content = unescape(content)
tree = etree.HTML(content)
# 查找包含“公考雷达”的标签
str1 = tree.xpath('//p[contains(text(), "公考雷达")] | //a[contains(text(), "公考雷达")]/.. | //div[contains(text(), "公考雷达")]')
# 查找包含“附件:”或“附件:”或“常见office文件后缀”的标签
str2 = tree.xpath('//a[re:match(text(), "附件(\w+)?(:|:)") or re:match(text(), "(.doc|.xls|.ppt|.pdf)")]/..', namespaces={
"re": "http://exslt.org/regular-expressions"})
str3 = tree.xpath('//p[re:match(text(), "^(附件)(\w+)?(:|:)") or re:match(text(), "(.doc|.xls|.ppt|.pdf)")]', namespaces={
"re": "http://exslt.org/regular-expressions"})
str4 = tree.xpath('//span[re:match(text(), "附件(\w+)?(:|:)") or re:match(text(), "(.doc|.xls|.ppt|.pdf)")]/../..', namespaces={
"re": "http://exslt.org/regular-expressions"})
str5 = tree.xpath('//em[re:match(text(), "附件(\w+)?(:|:)") or re:match(text(), "(.doc|.xls|.ppt|.pdf)")]/../..', namespaces={
"re": "http://exslt.org/regular-expressions"})
# 查找href中包含gongkaoleida的标签
str6 = tree.xpath('//*[re:match(@href, "gongkaoleida")]', namespaces={
"re": "http://exslt.org/regular-expressions"})
# 数据清洗
for i in str1 + str2 + str3 + str4 + str5 + str6:
p1 = html.tostring(i)
p2 = unescape(p1.decode('utf-8'))
content = content.replace(p2, '')
# 压缩代码
content = htmlmin.minify(content, remove_empty_space=True, remove_comments=True)
print(content)
XPath + 正则
その方法は次のとおりです。
予防
- lxmlで XPath の通常のメソッド ( )を使用する場合は、次のように
re:match()
名前空間 ( ) と組み合わせて使用する必要があります。namespaces={"re": "http://exslt.org/regular-expressions"}
str6 = tree.xpath('//*[re:match(@href, "gongkaoleida")]', namespaces={ "re": "http://exslt.org/regular-expressions"})
- Scrapyで XPath の通常のメソッド ( )を使用する
re:match()
場合、次のような名前空間を入力する必要はありません。attachment_title_list = response.xpath('//a[re:match(text(), "(.doc|.xls|.ppt|.pdf)")]/text()').getall()