这让我发疯了,我已经挣扎了很多小时。任何帮助将非常感激。
我正在使用PyQuery 1.2.9(在之上构建lxml
)来抓取此URL。我只想获取此.linkoutlist
部分中所有链接的列表。
这是我的全部要求:
response = requests.get('http://www.ncbi.nlm.nih.gov/pubmed/?term=The%20cost-effectiveness%20of%20mirtazapine%20versus%20paroxetine%20in%20treating%20people%20with%20depression%20in%20primary%20care')
doc = pq(response.content)
links = doc('#maincontent .linkoutlist a')
print links
但这返回一个空数组。如果我改用此查询:
links = doc('#maincontent .linkoutlist')
然后我得到这个HTML:
<div xmlns="http://www.w3.org/1999/xhtml" xmlns:xi="http://www.w3.org/2001/XInclude" class="linkoutlist">
<h4>Full Text Sources</h4>
<ul>
<li><a title="Full text at publisher's site" href="http://meta.wkhealth.com/pt/pt-core/template-journal/lwwgateway/media/landingpage.htm?issn=0268-1315&volume=19&issue=3&spage=125" ref="itool=Abstract&PrId=3159&uid=15107654&db=pubmed&log$=linkoutlink&nlmid=8609061" target="_blank">Lippincott Williams & Wilkins</a></li>
<li><a href="http://ovidsp.ovid.com/ovidweb.cgi?T=JS&PAGE=linkout&SEARCH=15107654.ui" ref="itool=Abstract&PrId=3682&uid=15107654&db=pubmed&log$=linkoutlink&nlmid=8609061" target="_blank">Ovid Technologies, Inc.</a></li>
</ul>
<h4>Other Literature Sources</h4>
...
</div>
因此,父选择器确实返回带有很多<a>
标签的HTML 。这似乎也是有效的HTML。
更多实验表明xmlns
,出于某种原因,lxml不喜欢开头div上的属性。
如何在lxml中忽略它,而像常规HTML一样解析它?
更新:正在尝试ns_clean
,仍然失败:
parser = etree.XMLParser(ns_clean=True)
tree = etree.parse(StringIO(response.content), parser)
sel = CSSSelector('#maincontent .rprt_all a')
print sel(tree)
您需要处理名称空间,包括一个空的名称空间。
工作解决方案:
from pyquery import PyQuery as pq
import requests
response = requests.get('http://www.ncbi.nlm.nih.gov/pubmed/?term=The%20cost-effectiveness%20of%20mirtazapine%20versus%20paroxetine%20in%20treating%20people%20with%20depression%20in%20primary%20care')
namespaces = {'xi': 'http://www.w3.org/2001/XInclude', 'test': 'http://www.w3.org/1999/xhtml'}
links = pq('#maincontent .linkoutlist test|a', response.content, namespaces=namespaces)
for link in links:
print link.attrib.get("title", "No title")
打印与选择器匹配的所有链接的标题:
Full text at publisher's site
No title
Free resource
Free resource
Free resource
Free resource
或者,只需将设置为parser
,"html"
而忽略名称空间:
links = pq('#maincontent .linkoutlist a', response.content, parser="html")
for link in links:
print link.attrib.get("title", "No title")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句