python - 按标题类型拆分 HTML div 后,如何提取我感兴趣的内容?

标签 python html xml xpath lxml

给定一个页面,例如 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 siblingclass =“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/

相关文章:

Python OpenCV : Using matchTemplate

html - Css 对 Angular 线 Div

android - 如何让一个数字替换 android :hint, 的一个字母,而提示仍然存在,直到我全部替换它? (安卓工作室)

javacode/Id 中的 java android 空间

python - 在 Python 中解压包含 bool 值的结构

python - 在 Python 中发布 HTTP : Reserved XML Name. 行 : 2, 字符:40

python - 向量化嵌套循环

javascript - 如何在 echo 中包含 onchange 中的 javascript 方法调用

javascript - 在 HTML 输入字段中禁用撤消/重做

c++ - 我想允许 xml 文件并发读取访问