合理的な解析されたを返しながら、空の結果を返します。私は、伝統的に、彼らはそのlxmlのはBeautifulSoupよりも厳しいと言っている、しかし、私は何を得ることはありませんが、以下であることを理解してください:lxmlの解析HTML beautifulsoupが
(基本的に私は要求しています私はhttp://basic.10jqka.com.cn/600000/company.htmlのようなリンクが仕事をして、言ったように
In [1]: headers = {'User-Agent': ''}
In [2]: url = 'http://basic.10jqka.com.cn/600219/company.html'
In [3]: headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0'}
In [6]: import lxml.html
In [7]: res = requests.get(url, headers=headers)
In [8]: tree = lxml.html.fromstring(res.content)
---------------------------------------------------------------------------
ParserError Traceback (most recent call last)
<ipython-input-8-b512dc78ed68> in <module>()
----> 1 tree = lxml.html.fromstring(res.content)
/home/jgu/repos/.venv36/lib/python3.6/site-packages/lxml/html/__init__.py in fromstring(html, base_url, parser, **kw)
874 else:
875 is_full_html = _looks_like_full_html_unicode(html)
--> 876 doc = document_fromstring(html, parser=parser, base_url=base_url, **kw)
877 if is_full_html:
878 return doc
/home/jgu/repos/.venv36/lib/python3.6/site-packages/lxml/html/__init__.py in document_fromstring(html, parser, ensure_head_body, **kw)
763 if value is None:
764 raise etree.ParserError(
--> 765 'Document is empty')
766 if ensure_head_body and value.find('head') is None:
767 value.insert(0, Element('head'))
ParserError: Document is empty
In [12]: from bs4 import BeautifulSoup
In [13]: soup = BeautifulSoup(res.content, 'html.parser')
In [14]: soup.title
Out[14]: <title>南山铝业(600219) 公司资料_F10_同花顺金融服务网</title>
In [15]: sel_query = (
...: '#detail > div.bd > table > tbody > tr:nth-of-type(1) > '
...: 'td:nth-of-type(2) > span'
...:)
In [16]: soup.select(sel_query)
Out[16]: [<span>山东南山铝业股份有限公司</span>]
In [17]: soup.select(sel_query)[0].text
Out[17]: '山东南山铝业股份有限公司'
)のウェブページは、中国語で、そして。いくつかのスパンを選択するために期待し、同様のページがエラーなしで動作することができますが、いくつかのリンクがlxmlのためだけに解析することはできません。
解析結果が空のときにbs4に戻ることができますが、lxmlがソースから妥当なdomツリーを解析できない理由を理解したいと思います。ありがとう
私はPython 2を使用しています。私の質問を編集しました –
一部のページは両方のパーサで動作し、いくつかのページは 'bs'でのみ動作するのですか? – stamaimer
はい。多くのリンクlxmlは動作しますが、いくつかの例では失敗し、何も返しません –