2012-02-16 18 views
1

我使用lxml來刮取html。此代碼有效。爲什麼lxml.html.parse()結尾的斜槓很重要?

lxml.html.parse("http://google.com/") 

此代碼沒有。

lxml.html.parse("http://google.com") 

爲什麼URL末尾的斜槓很重要?謝謝。

要清楚,這裏是python從後面的代碼給我的錯誤日誌。

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/home/davidfaux/epd-7.2-2-rh5-x86/lib/python2.7/site-packages/lxml/html/__init__.py", line 692, in parse 
    return etree.parse(filename_or_url, parser, base_url=base_url, **kw) 
    File "lxml.etree.pyx", line 2953, in lxml.etree.parse (src/lxml/lxml.etree.c:56204) 
    File "parser.pxi", line 1533, in lxml.etree._parseDocument (src/lxml/lxml.etree.c:82287) 
    File "parser.pxi", line 1562, in lxml.etree._parseDocumentFromURL (src/lxml/lxml.etree.c:82580) 
    File "parser.pxi", line 1462, in lxml.etree._parseDocFromFile (src/lxml/lxml.etree.c:81619) 
    File "parser.pxi", line 1002, in lxml.etree._BaseParser._parseDocFromFile (src/lxml/lxml.etree.c:78528) 
    File "parser.pxi", line 569, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:74472) 
    File "parser.pxi", line 650, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:75363) 
    File "parser.pxi", line 588, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:74665) 
IOError: Error reading file 'http://google.com': failed to load HTTP resource 
+0

它對我有或沒有'/'工作正常。 – RanRag 2012-02-16 00:10:28

+0

有趣。在Python解釋器中,'http:// google.com /'適用於我,但不適用'http:// google.com'。 – dangerChihuahua007 2012-02-16 00:11:44

回答

1

由於沒有斜槓,Google不會向您發送頁面,而是向您發送重定向。事實上,它正在使用斜線將您重定向到URL!重定向的主體可能是空的。

+0

謝謝,但如果我在Chrome上訪問https:// www.google.com /',我認爲Chrome會將我重定向到https:// www.google.com。 – dangerChihuahua007 2012-02-16 00:05:21

+1

確實如此。但是,如果您使用urllib提取這些網址,您會看到我描述的行爲。谷歌做了許多神祕而微妙的事情。 – 2012-02-16 00:14:24

+1

不幸的是,如何在Chrome瀏覽器的網址欄中顯示某個網址與實際網址無關。 Chrome習慣性地去掉部分網址,以使網址看起來不那麼具有威脅性或某種東西。你不能依靠它。 – kindall 2012-02-16 00:21:31