【发布时间】:2021-12-28 17:52:24
【问题描述】:
<a href="/what-to-watch/fan-favorites/?ref_=hm_fanfav_sm" class="ipc-title ipc-title--
subsection-title ipc-title--baseAlt ipc-title--on-textPrimary ipc-title-link-wrapper"
tabindex="0"><h3 class="ipc-title__text">Fan favorites<svg width="24" height="24"
xmlns="http://www.w3.org/2000/svg" class="ipc-icon ipc-icon--chevron-right-inline ipc-
icon--inline ipc-title-link-chevron" viewBox="0 0 24 24" fill="currentColor"
role="presentation"><path d="M5.622.631A2.153 2.153 0 0 0 5 2.147c0 .568.224 1.113.622
1.515l8.249 8.34-8.25 8.34a2.16 2.16 0 0 0-.548 2.07c.196.74.768 1.317 1.499 1.515a2.104
2.104 0 0 0 2.048-.555l9.758-9.866a2.153 2.153 0 0 0 0-3.03L8.62.61C7.812-.207 6.45-.207
5.622.63z"></path></svg></h3><div class="ipc-title__description">This week's top TV and
movies</div></a>
和
<a class="ipc-poster-card__title ipc-poster-card__title--clamp-2
ipc-poster-card__title--clickable" aria-label="View title page for
Shang-Chi and the Legend of the Ten Rings" href="/title/tt9376612/?
ref_=watch_fanfav_tt_t_2"><span data-testid="title">Shang-Chi and the
Legend of the Ten Rings</span></a>
是我希望我的蜘蛛用代码抓取的网站的 HTML 结构吗:
import scrapy
from scrapy.crawler import CrawlerProcess
class imdb_favorites(scrapy.Spider):
name = "imdB Favorites"
def start_requests(self):
url = "https://www.imdb.com"
yield scrapy.Request(url = url,
callback = self.parse_front)
def parse_front(self, response):
# Get the link of 'What to watch section'
fan_favorites = response.css('div.fan-picks>a::attr(href)')
link_to_follow = fan_favorites.extract()
for i in link_to_follow:
url2 = url + i
print(url2)
yield response.follow(url = url2,
callback = self.parse_2)
def parse_2(self, response):
# Gets the links of the movies in what to watch section.
what_to_watch = response.css('a.ipc-poster-card__title::attr(href)').extract()
for a in what_to_watch:
url3 = "https://www.imdb.com" + a
print(url3)
yield response.follow(url = url3,
callback = parse_3)
process= CrawlerProcess()
process.crawl(imdb_favorites)
process.start()
问题是 print() 函数在 for 循环中不起作用,所以我看不到我的代码是否正确爬行,所以我无法进一步自学。感谢您的关注。
【问题讨论】:
-
打印功能应该在 for 循环中工作。如果
link_to_follow和what_to_watch有值,你能用 print() 检查吗?此外,您在 parse_front 中可能有错误,您使用url2 = url + i,而 url 未在 parse_front 中分配,而是在 start_requests 中分配。您是否想在 start_requests 和 parse_front 中使用self.url? -
@PatrickKlein 我已按照您提供的所有说明进行操作,并且 parse_front 运行良好且干净(至少对于打印功能而言)。但是 parse_2 部分既不打印 what_to_watch 也不打印 url3 也许我在将爬虫导航到 parse_2 时在选择器中犯了一个错误
标签: scrapy css-selectors