给定一个页面,例如 this ,通过两个作业(我们暂时忽略“打开应用程序”)一个接一个地进行完整描述,我可以通过应用以下 XPath 来检测是否存在与关键字匹配的作业:
//*[self::h2 or self::h3 or self::h4][contains(., 'Country Manager')]
通过Python:
import urllib2
import lxml.html as lh
url = 'http://jobs.kelkoo.co.uk/'
response = urllib2.urlopen(url)
content = response.read()
root = lh.fromstring(content)
job_titles = root.xpath("//*[self::h2 or self::h3 or self::h4][contains(., 'Country Manager')]")
然后我可以确定涉及哪种类型:
tags = [e.tag for e in titles]
知道我们正在处理一个 <h2>
,我希望提取个人工作规范。我知道我可以描述每个 <h2>
使用以下内容:
//div[count(preceding-sibling::h2)=1]
但是如何将有关职位名称所在位置的知识与其标签类型以及上述描述联系起来?
我尝试将关键字放回到上面描述的 XPath 中,但我被告知这不是一个有效的表达式:
//div[count(preceding-sibling::h2[contains(text(), 'Country Manager')]=1]
最佳答案
查找following div
sibling与class =“jobspecs”
:
for title in job_titles:
print(title.text_content())
for spec in title.xpath("following-sibling::div[@class='jobspecs']/ul/li/span[@class='label']"):
spec_name = spec.text_content().strip()
spec_value = spec.xpath("following-sibling::text()")[0].strip()
print(spec_name, spec_value)
print("----")
打印:
Country Manager - Uk
Contract type: Permanent
Hours per week: 40
Site: London
----
关于python - 按标题类型拆分 HTML div 后,如何提取我感兴趣的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35257803/