在Python Scrapy中选择具有特定ID模式的所有元素
我正在使用scrapy这个工具来抓取一个网站的内容。
我想选择所有ID格式为'result_%s'的元素,其中%s可以是任何整数。
sites.select('//*[@id="result_1"]')
我该怎么做呢?
1 个回答
6
在Scrapy中,提取网页信息的主要方式是使用Selector
。最常用的方式是通过Xpath表达式来使用Scrapy的选择器。
Xpath有一些很实用的功能,其中之一就是contains()
。你可以在你的爬虫代码中这样使用它:
from scrapy.spider import Spider
from scrapy.selector import Selector
class ExampleSpider(Spider):
name = "exampleSpider"
start_urls = ["http://example.com/sitemap.html"]
def parse(self, response):
sel = Selector(response)
results = sel.xpath("//*[contains(@id, 'result_')]")
for result in results:
#do something with the results here
print result.extract()
这个函数会检查第二个参数是否是第一个参数的子字符串。
如果你想了解更多关于如何构建你的爬虫和从网页提取数据的信息,可以参考官方Scrapy教程,这是一个很好的资源。