如何使用scrapy中的选择器解析此特定的html正文?

时间:2018-09-19 13:48:56

标签: python scrapy web-crawler scrapy-spider

我正在尝试从特定网站抓取特定项目。

代码段如下:

    # Constant Div Path variables for Parameters.
    pathForMovieCardContainer = '//div[@class="card-container wow fadeIn movie-card-container"]'
    pathForMovieName = 'div[@class="card-container wow fadeIn movie-card-container"]//div[@class="cards"]//div[@class="card-details"]//div[@class="card-right"]//div[@class="card-title"]/text()'
    str_slash = "/"
    movies_dict = []
    movies = response.xpath(pathForMovieCardContainer).extract()

    for movie in movies:
        print("***********************")
        print(movie)
        mov = TestDataCrawlersItem()
        mov['name'] = Selector(text=movie).xpath(pathForMovieName).extract()

我无法从路径'div[@class="card-container wow fadeIn movie-card-container"]//div[@class="cards"]//div[@class="card-details"]//div[@class="card-right"]//div[@class="card-title"]/text()'获取文本,我不确定pathForMovieName的结构是否正确。有人可以帮我弄这个吗?谢谢!

1 个答案:

答案 0 :(得分:0)

当需要通过元素的类名选择元素时,使用.css()比使用.xpath()更容易。您可以尝试这样的事情:

movies = response.css('.movie-card-container')
for movie in movies:
    item = TestDataCrawlersItem()
    item['name'] = movie.css('.card-title::text').get()

有关CSS选择器的更多信息:https://parsel.readthedocs.io/en/latest/usage.html