Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python BeautifulSoup错误地解析页面,并且不';找不到链接_Python_Html Parsing_Beautifulsoup_Urllib2_Python 2.7 - Fatal编程技术网

Python BeautifulSoup错误地解析页面,并且不';找不到链接

Python BeautifulSoup错误地解析页面,并且不';找不到链接,python,html-parsing,beautifulsoup,urllib2,python-2.7,Python,Html Parsing,Beautifulsoup,Urllib2,Python 2.7,下面是python 2.7.2中的一段简单代码,它获取站点并从给定站点获取所有链接: import urllib2 from bs4 import BeautifulSoup def getAllLinks(url): response = urllib2.urlopen(url) content = response.read() soup = BeautifulSoup(content, "html5lib") return soup.find_all("a

下面是python 2.7.2中的一段简单代码,它获取站点并从给定站点获取所有链接:

import urllib2
from bs4 import BeautifulSoup

def getAllLinks(url):
    response = urllib2.urlopen(url)
    content = response.read()
    soup = BeautifulSoup(content, "html5lib")
    return soup.find_all("a")

links1 = getAllLinks('http://www.stanford.edu')
links2 = getAllLinks('http://med.stanford.edu/')

print len(links1)
print len(links2)
问题是它在第二种情况下不起作用。它打印102和0,而在第二个站点上显然有链接。BeautifulSoup不会抛出解析错误,它可以很好地打印标记。我怀疑这可能是由med.stanford.edu的源代码中的第一行引起的,该行说它是xml(即使内容类型是:text/html):



我不知道如何设置Beauty来忽略它,或者解决方法。我使用html5lib作为解析器,因为我对默认的解析器(不正确的标记)有问题。

你完全正确,问题在于
当文档声称是XML时,我发现lxml解析器提供了最好的结果。尝试您的代码,但使用lxml解析器而不是html5lib可以找到300个链接。

有一个语法错误:您没有为
parseOnlyThese=
提供任何参数。很好,您如此轻松地缩小了范围,我担心编码也可能是原因之一。我希望图书馆能提供一些更安全的方法。例如,可能有一个站点,其中这一行将是第二行而不是第一行,或者这一行的开头可能有一些空白。也许正则表达式就足够了,但仍有许多边缘情况。解析库的全部目的就是从中抽象出来,但我想web从来并没有那个么简单和直接。重要的是,这解决了问题,谢谢。确实,lxml解析器解决了这个问题。在选择html5lib之前,我尝试安装lxml,但在Windows上安装它时遇到了问题,正如在这个问题中一样,所以我决定使用html5lib,因为它安装时没有问题。在您的回答之后,我决定再试一次,并根据这个回答使用Python2.7的编译二进制文件安装了lxml。谢谢,我将把解析器改为lxml,因为它不仅解决了这个问题,而且在文档中被推荐为更快的解析器。
<?xml version="1.0" encoding="iso-8859-1"?>
    content = response.read()
    content = "\n".join(response.readlines()[1:])
content = response.read()
if content.startswith("<?xml"):
    content = "\n".join(content.split("\n")[1:])