Skip to main content
 首页 » 编程设计

python之垃圾。 LinkExtractor 中的意外符号

2025年04月02日14lhb25

我正在研究 Scrapy 库并尝试制作一个小爬虫。

这是爬虫的规则:

rules = ( 
    Rule(LinkExtractor(restrict_xpaths='//div[@class="wrapper"]/div[last()]/a[@class="pagenav"][last()]')), 
    # Rule(LinkExtractor(restrict_xpaths='//span[@class="update_title"]/a'), callback='parse_item'), 
) 

但我收到此错误消息:

DEBUG: Crawled (200) <GET http://web/category.php?id=4&> (referer: None) 
DEBUG: Crawled (404) <GET http://web/%0D%0Acategory.php?id=4&page=2&s=d> (referer: http://web/category.php?id=4&) 
DEBUG: Ignoring response <404 http://web/%0D%0Acategory.php?id=4&page=2&s=d>: HTTP status code is not handled or not allowed 

这是 html 的样子:

<a class="pagenav" href=" category.php?id=4&page=8&s=d& ">8</a> 
| 
<a class="pagenav" href=" category.php?id=4&page=9&s=d& ">9</a> 
| 
<a class="pagenav" href=" category.php?id=4&page=10&s=d& ">10</a> 
|          
<a class="pagenav" href=" category.php?id=4&page=2&s=d& ">Next ></a> 

谁能解释一下这个 %0D%0A 是从哪里来的? 亲切的问候,马克西姆。

更新: 我做了一个简单的函数

def process_value(value): 
    value = value.strip() 
    print value 
    return value 

并将规则更改为

rules = ( 
    Rule(LinkExtractor(restrict_xpaths='//div[@class="wrapper"]/div[last()]/a[@class="pagenav"][last()]', process_value=process_value)), 
    # Rule(LinkExtractor(restrict_xpaths='//span[@class="update_title"]/a'), callback='parse_item'), 
) 

打印命令打印这个:

Crawled (200) <GET http://web/category.php?id=4&>(referer: None) 
http://web/ 
category.php?id=4&page=2&s=d& 
Crawled (404) <GET http://web/%0D%0Acategory.php?%0D=&id=4&page=2&s=d>(referer: http://web/category.php?id=4&) 

请您参考如下方法:

%0D 和 %0A 是 HTML 编码中的 CR 和 LF 字符。

您解析的网站作者将字符放入 HTML 文档中。我认为,偶尔,因为它们在 IDE 或浏览器中不可见。

解释不可见字符的含义:

还有更多关于编码的信息 http://www.w3schools.com/tags/ref_urlencode.asp

我建议你去掉所有需要以这种方式获取的链接:

href = href.strip()