我是刮擦的新手,写我的第一个蜘蛛为网站制作一个刮擦蜘蛛
,类似于 https://blogs.webmd.com/diabetes/default.htm我想抓取标题,然后导航到每篇文章,抓取每篇文章的文本内容。
我已经尝试使用规则和链接提取器,但它无法导航到下一页并提取。 我收到错误:蜘蛛错误处理 https://blogs.webmd.com/diabetes/default.htm>(参考:无(
下面是我的代码
import scrapy
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
class MedicalSpider(scrapy.Spider):
name = 'medical'
allowed_domains = ['https://blogs.webmd.com/diabetes/default.htm']
start_urls = ['https://blogs.webmd.com/diabetes/default.htm']
Rules = (Rule(LinkExtractor(allow=(), restrict_css=('.posts-list-post-content a ::attr(href)')), callback="parse", follow=True),)
def parse(self, response):
headline = response.css('.posts-list-post-content::text').extract()
body = response.css('.posts-list-post-desc::text').extract()
print("%s : %s" % (headline, body))
next_page = response.css('.posts-list-post-content a ::attr(href)').extract()
if next_page:
next_href = next_page[0]
next_page_url = next_href
request = scrapy.Request(url=next_page_url)
yield request
请引导新手在scrapy中使此蜘蛛适合每页上的多篇文章。
通常,当使用scrapy时,每个响应都通过解析回调进行解析。主要的parse
方法是为每个start_urls
获得的初始响应的回调。
然后,该解析函数的目标应该是"识别文章链接",并为每个链接发出请求。然后,这些响应将由另一个回调解析,例如parse_article
,然后从该特定文章中提取所有内容。
你甚至不需要那个LinkExtractor
.考虑:
import scrapy
class MedicalSpider(scrapy.Spider):
name = 'medical'
allowed_domains = ['blogs.webmd.com'] # Only the domain, not the URL
start_urls = ['https://blogs.webmd.com/diabetes/default.htm']
def parse(self, response):
article_links = response.css('.posts-list-post-content a ::attr(href)')
for link in article_links:
url = link.get()
if url:
yield response.follow(url=url, callback=self.parse_article)
def parse_article(self, response):
headline = 'some-css-selector-to-get-the-headline-from-the-aticle-page'
# The body is trickier, since it's spread through several tags on this particular site
body = 'loop-over-some-selector-to-get-the-article-text'
yield {
'headline': headline,
'body': body
}
我没有粘贴完整的代码,因为我相信你仍然想要一些兴奋来学习如何做到这一点,但你可以在这个要点上找到我想出的东西
请注意,parse_article
方法返回字典。这些正在使用Scrapy的项目管道。您可以通过使用以下方法运行代码来获得简洁的 json 输出: scrapy runspider headlines/spiders/medical.py -o out.json