使用 scrapy 或 selenium 从 div class 中提取 h1 文本
Extract h1 text from div class with scrapy or selenium
我正在使用 python 和 scrapy,selenium.I 想从 div class 内的 h1 标签中提取文本。
例如:
<div class = "example">
<h1>
This is an example
</h1>
</div>
这是我试过的代码:
for single_event in range(1,length_of_alllinks):
source_link.append(alllinks[single_event])
driver.get(alllinks[single_event])
s = Selector(response)
temp = s.xpath('//div[@class="example"]//@h1').extract()
print temp
title.append(temp)
print title
每次我尝试不同的方法时,我得到的都是一个空列表。
现在,我想提取 "This is an example" 即 h1 文本并将其存储或附加到列表中,即在我的示例标题中。
喜欢:
温度 = ['This is an example']
有一次,在您的 HTML 中, class 属性似乎是 "example" 但在您的代码中,您正在寻找其他 class 值;至少对于 XPath 查询,请记住您是按 exact 属性值搜索的。您可以使用类似的东西:
s.xpath('//div[contains(@class, "example")]')
查找具有 "example" class 但可能还有其他 class 的元素。我不确定这是一个错误还是您的实际代码。此外,HTML 中 class 属性的“=”符号周围有空格这一事实可能对某些解析器也没有帮助。
其次,您在 s.xpath
中使用的查询似乎有误。尝试这样的事情:
temp = s.xpath('//div[@class="example"]/h1').extract()
从您的代码中不清楚 s
是什么,所以我假设 extract()
方法按照您的想法行事。也许更干净的代码示例可以帮助我们帮助您。
尝试以下操作来提取预期的文本:
s.xpath('//div[@class="example"]/h1/text()').extract()
我正在使用 python 和 scrapy,selenium.I 想从 div class 内的 h1 标签中提取文本。 例如:
<div class = "example">
<h1>
This is an example
</h1>
</div>
这是我试过的代码:
for single_event in range(1,length_of_alllinks):
source_link.append(alllinks[single_event])
driver.get(alllinks[single_event])
s = Selector(response)
temp = s.xpath('//div[@class="example"]//@h1').extract()
print temp
title.append(temp)
print title
每次我尝试不同的方法时,我得到的都是一个空列表。
现在,我想提取 "This is an example" 即 h1 文本并将其存储或附加到列表中,即在我的示例标题中。 喜欢: 温度 = ['This is an example']
有一次,在您的 HTML 中, class 属性似乎是 "example" 但在您的代码中,您正在寻找其他 class 值;至少对于 XPath 查询,请记住您是按 exact 属性值搜索的。您可以使用类似的东西:
s.xpath('//div[contains(@class, "example")]')
查找具有 "example" class 但可能还有其他 class 的元素。我不确定这是一个错误还是您的实际代码。此外,HTML 中 class 属性的“=”符号周围有空格这一事实可能对某些解析器也没有帮助。
其次,您在 s.xpath
中使用的查询似乎有误。尝试这样的事情:
temp = s.xpath('//div[@class="example"]/h1').extract()
从您的代码中不清楚 s
是什么,所以我假设 extract()
方法按照您的想法行事。也许更干净的代码示例可以帮助我们帮助您。
尝试以下操作来提取预期的文本:
s.xpath('//div[@class="example"]/h1/text()').extract()