Python 告诉基于contains()的XPath查询在到达字母后停止?
我为给定的关键字刮取各种作业页面,并在有匹配项时提取标题和链接Python 告诉基于contains()的XPath查询在到达字母后停止?,python,html,xml,xpath,lxml,Python,Html,Xml,Xpath,Lxml,我为给定的关键字刮取各种作业页面,并在有匹配项时提取标题和链接 XPATH_MAPPING_SINGLE_PAGE = {'heading' : "//*[self::h2 or self::h3 or self::h4 or self::dt][contains(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '%s')]"} XPATH_MAPPING_HYPERLINKS = {'href'
XPATH_MAPPING_SINGLE_PAGE = {'heading' : "//*[self::h2 or self::h3 or self::h4 or self::dt][contains(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '%s')]"}
XPATH_MAPPING_HYPERLINKS = {'href': "//a[contains(translate(normalize-space(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '%s')]/@href",
'text': "//a[contains(translate(normalize-space(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '%s')]"}
import urllib2
import urlparse
import lxml.html as lh
response = urllib2_urlopen(url)
content = response.read()
root = lh.fromstring(content)
titles_and_links = get_individual_job_titles_and_hyperlinks(root, keyword)
def get_individual_job_titles_and_hyperlinks(root, keyword):
texts = [element.text_content().strip() for element in root.xpath(XPATH_MAPPING_HYPERLINKS['text'] % keyword)]
hrefs = root.xpath(XPATH_MAPPING_HYPERLINKS['href'] % keyword)
return zip(texts, hrefs)
这是相当可靠的工作。然而,对于一个像“工程师”这样的页面,它会从中提取单个工程工作,但也会提取一个指向该公司工程博客页面的链接:
>>print title_and_links
[('Engineering Blog', '//engineering.gosquared.com/'), ('Software Engineer', '/careers/software-engineer/'), ('Engineering Blog', '//engineering.gosquared.com/')]
这显然是因为我的XPath基于contains()
。一旦找到文本“Engineer”,它将认为它是匹配的,因此解释了为什么“Engineering”链接也会被选中
如何修改XPath,使其不会出现这些误报?更新后的XPath需要知道在关键字结束后立即停止,可能需要一些点字(空格、连字符、句点、逗号等),而不是一个字母,因此仍然可以正确地拾取链接文本,如:
- 机械工程师
- 药剂师
- 保健科顾问
- 等等
这是否可以通过XPath实现,而不需要添加正则表达式来使用标点或空格?我假设我们不能依赖页面上可能出现职务的任何特定部分 但是,我很确定,您可以避免查看
页眉
和页脚
元素。检查家长:
//*
[self::h2 or self::h3 or self::h4 or self::dt]
[contains(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '%s')]
[not(ancestor::footer) and not(ancestor::header)]
在这种情况下,这将有助于不匹配工程博客
,因为它位于页脚。我假设我们不能依赖页面上可能出现职位的任何特定部分。-事实上,这个页面只是一个例子,工程页面的链接可以在任何地方。