python - Scrapy - 使用正则表达式选择 xpath

标签 python python-2.7 xpath web-scraping scrapy

我正在抓取的部分 html 如下所示:

<h2> <span class="headline" id="Profile">Profile</span></h2>
<ul><li> <b>Name</b> Albert Einstein
</li><li> <b>Birth Name:</b> Alberto Ein
</li><li> <b>Birthdate:</b> December 24, 1986
</li><li> <b>Birthplace:</b> <a href="/Ulm" title="Dest">Ulm</a>, Germany
</li><li> <b>Height:</b> 178cm
</li><li> <b>Blood Type:</b> A
</li></ul>

我想提取每个组件——比如姓名、出生名、生日等。

提取我做的名字:

a_name = response.xpath('//ul/li/b[contains(text(),"Name")]/../descendant::text()').extract()

然后我检查 a_name 不是一个空列表并调用:

"".join(a_name[2:]).strip()

我这样做是为了保持一致性,因为在 Birthplace 中,我只想提取文本,不包括所有 html 属性。所以我会选择德国的乌尔姆。

问题是当我使用 contains(text(), "Name") 时,Birth Name 的条目也匹配。构建选择器时如何避免这种情况?

使用正则表达式,我可以指定诸如 text() 匹配 ^Name.* 之类的内容,因为文本 Name 后面可能跟也可能不跟冒号和/或空格。

有没有办法使用正则表达式来解决这个问题?

最佳答案

如果你想使用正则表达式,你可以试试这个:

response.xpath('//ul/li/b[text()[re:test(., '^Name.*')]]/../descendant::text()') 

但你最好使用starts-with

response.xpath('//ul/li/b[starts-with(text(),"Name")]/../descendant::text()')

关于python - Scrapy - 使用正则表达式选择 xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45384382/

相关文章:

python - 将具有相同哈希值的两个键放入字典中

python - 连接相反的节点

python - 键盘事件未使用 pywin32 发送到窗口

python - 无法使用我的 scraper 中定义的 xpath 获取项目

xpath - 在 Dynamics AX、X++ 中,如何增加日期变量

python - Boost.Python TypeError : __init__() should return None not 'NoneType' - but no obvious linker or version problem

python - 将参数传递给 Flask 错误处理程序

ruby - 如何使用 ruby​​、xpath、rexml 从子上下文获取节点文本

python - 使用正则表达式 re.search 和 re.compile 的问题

精确字符串长度的Python正则表达式