xpath:如何提取 <strong> 元素之前、之内和之后的文本

Lea*_*AWK 4 python xpath scrapy web-scraping

我正在研究一个 Scrapy 蜘蛛,其中 xpath 用于提取所需的信息。源页面首先是通过使用网站的搜索功能生成的。例如,我的兴趣是获取标题中带有“计算机”的项目。在源页面上,由于搜索过程,所有“计算机”都以粗体显示。并且“计算机”可以在标题的开头、中间或结尾。有些项目的标题中没有“计算机”。请参阅以下示例:

Example 1: ("computer" at the beginning)
<a class="title" href="whatever1">
<strong> Computer </strong>
, used
</a>  

Example 2: ("computer" in the middle)
<a class="title" href="whatever2">
Low price
<strong> computer </strong>
, great deal
</a> 

Example 3: ("computer" at the end)
<a class="title" href="whatever3">
Don't miss this
<strong> Computer </strong>
</a>

Example 4: (no keyword of "computer")
<a class="title" href="whatever4">
Best laptop deal ever!      
</a>
Run Code Online (Sandbox Code Playgroud)

我试过的 xpath 代码.//a[@class="title"]/text()只会生成元素之后strong部分。对于上面的4个例子,我会得到以下结果:

Example 1:
, used

Example 2:
, great deal

Example 3: (Nothing)


Example 4:
Best laptop deal ever!
Run Code Online (Sandbox Code Playgroud)

我需要一个 xpath 代码来涵盖所有这四种情况并收集每个项目的完整标题。

ale*_*cxe 5

最简单的方法是搜索所有“文本”节点并“加入”它们:

"".join(response.xpath('.//a[@class="title"]//text()').extract())
Run Code Online (Sandbox Code Playgroud)

注意text()这里的关键修复之前的双斜线。