Skip to main content
 首页 » 编程设计

python之使用 scrapy 抓取项目

2025年05月04日24jyk

我已经编写了以下蜘蛛程序来抓取 webmd 站点以供患者评论

from scrapy.spider import BaseSpider 
from scrapy.selector import HtmlXPathSelector 
 
 
class MySpider(BaseSpider): 
    name = "webmd" 
    allowed_domains = ["webmd.com"] 
    start_urls = ["http://www.webmd.com/drugs/drugreview-92884-Boniva"] 
 
    def parse(self, response): 
        hxs = HtmlXPathSelector(response) 
        titles = hxs.select("//p") 
        title = titles.select("//p[contains(@class, 'comment')and contains(@style, 'display:none')]/text()").extract() 
        print(title) 

执行这段代码会得到我想要的输出,但有很多重复,即相同的注释至少重复了 10 次。 帮我解决这个问题。

请您参考如下方法:

你可以像这样重写你的爬虫代码:

import scrapy 
 
# Your Items  
class ReviewItem(scrapy.Item): 
    review = scrapy.Field() 
 
 
class WebmdSpider(scrapy.Spider): 
    name = "webmd" 
    allowed_domains = ["webmd.com"] 
    start_urls = ['http://www.webmd.com/drugs/drugreview-92884-Boniva'] 
 
    def parse(self, response): 
        titles = response.xpath('//p[contains(@id, "Full")]') 
        for title in titles: 
            item = ReviewItem() 
            item['review'] = title.xpath('text()').extract_first() 
            yield item 
 
        # Checks if there is a next page link, and keeping parsing if True     
        next_page = response.xpath('(//a[contains(., "Next")])[1]/@href').extract_first() 
        if next_page: 
            yield scrapy.Request(response.urljoin(next_page), callback=self.parse) 

它只选择没有重复的完整客户评论并将它们保存在 Scrapy Items 中. 注意:您可以使用更方便的快捷方式 response 而不是 HtmlXPathSelector。此外,我将已弃用的 scrapy.BaseSpider 更改为 scrapy.Spider。

要将评论保存为 csv 格式,您可以简单地使用 Scrapy Feed exports并在控制台中输入 scrapy crawl webmd -o reviews.csv。